簡體   English   中英

組合框SelectedItem變為空

[英]Combobox SelectedItem Becomes Null

我正在嘗試制作在對象之間切換的ComboBox。 一般要點是,對象具有出現在ComboBox中的Key和理論上可以是任何東西的Data組件。 當鍵只是一個字符串時,數據組件很復雜。 對於下面的示例,數據只是一個Uri,實際上,數據的類型無關緊要。

基本目的是將ComboBox的SelectedItem綁定到模型,以便可以通過其他交互來修改SelectedItem的數據。

設置代碼后,將幾個項目添加到ComboBox,然后選擇SelectedItem作為第一個元素。 那很好。 然后,當我單擊按鈕時,在拋出異常的位置將SelectedItem分配為null。

為什么將SelectedItem分配為null?

這是完整的工作代碼; 我的目標是.NET 4.0,但我猜它並不太重要。 Xaml如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace Sandbox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public Model Model { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;

            Model = new Model();

            this.Model.Items.Add(
                new ObservableKeyValuePair<string, Uri>()
                {
                    Key = "Apple",
                    Value = new Uri("http://apple.com")
                });

            this.Model.Items.Add(
                new ObservableKeyValuePair<string, Uri>()
                {
                    Key = "Banana",
                    Value = new Uri("http://Banana.net")
                });

            this.Model.SelectedItem = this.Model.Items.First();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Model.SelectedItem.Value = new Uri("http://cranberry.com");
        }
    }

    public class TrulyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
    {
        public TrulyObservableCollection()
        {
            CollectionChanged += FullObservableCollectionCollectionChanged;
        }

        public TrulyObservableCollection(IEnumerable<T> pItems)
            : this()
        {
            foreach (var item in pItems)
            {
                this.Add(item);
            }
        }

        private void FullObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach (Object item in e.NewItems)
                {
                    ((INotifyPropertyChanged)item).PropertyChanged += ItemPropertyChanged;
                }
            }
            if (e.OldItems != null)
            {
                foreach (Object item in e.OldItems)
                {
                    ((INotifyPropertyChanged)item).PropertyChanged -= ItemPropertyChanged;
                }
            }
        }

        private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender, IndexOf((T)sender));
            OnCollectionChanged(args);
        }
    }

    public class ObservableKeyValuePair<TKey, TValue> :
        INotifyPropertyChanged,
        IEquatable<ObservableKeyValuePair<TKey, TValue>>
    {
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }

        public override bool Equals(object rhs)
        {
            var obj = rhs as ObservableKeyValuePair<TKey, TValue>;

            if (obj != null)
            {
                return this.Key.Equals(obj.Key);
            }

            return false;
        }

        public bool Equals(ObservableKeyValuePair<TKey, TValue> other)
        {
            return this.Key.Equals(other.Key);
        }

        public override int GetHashCode()
        {
            return this.Key.GetHashCode();
        }

        protected TKey _Key;
        public TKey Key
        {
            get
            {
                return _Key;
            }
            set
            {
                if (value is INotifyPropertyChanged)
                {
                    (value as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler(KeyChanged);
                }

                _Key = value;

                OnPropertyChanged("Key");
            }
        }
        void KeyChanged(object sender, PropertyChangedEventArgs e)
        {
            OnPropertyChanged("Key");
        }

        protected TValue _Value;
        public TValue Value
        {
            get
            {
                return _Value;
            }
            set
            {
                if (value is INotifyPropertyChanged)
                {
                    (value as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler(ValueChanged);
                }

                _Value = value;

                OnPropertyChanged("Value");
            }
        }
        void ValueChanged(object sender, PropertyChangedEventArgs e)
        {
            OnPropertyChanged("Value");
        }
    }

    public class Model : INotifyPropertyChanged
    {
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        public Model()
        {
            Items = new TrulyObservableCollection<ObservableKeyValuePair<string, Uri>>();
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }

        public TrulyObservableCollection<ObservableKeyValuePair<string, Uri>> Items { get; set; }
        public ObservableKeyValuePair<string, Uri> _SelectedItem = null;
        public ObservableKeyValuePair<string, Uri> SelectedItem
        {
            get
            {
                return Items.FirstOrDefault(x => _SelectedItem != null && x.Key == _SelectedItem.Key);
            }
            set
            {
                if (value == null)
                {
                    throw new Exception("This is the problem");
                }

                if (_SelectedItem != value)
                {
                    _SelectedItem = value;
                    OnPropertyChanged("SelectedItem");
                }
            }
        }
    }
}

Xaml:

<Window x:Class="Sandbox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Button Click="Button_Click" Content="Clsick Me"/>
        <ComboBox IsEditable="False" ItemsSource="{Binding Model.Items}" SelectedItem="{Binding Model.SelectedItem, Mode=TwoWay}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Key}">
                    </TextBlock>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </StackPanel>
</Window>

我完全無法解釋為什么“值”為空。

該值變為空,因為您正試圖分配一個不在集合中的選定項目值

根本問題在於Selector.OnItemsChanged的實現。 在方法結束時,當前的SelectedItem為空。

我通過派生一個新的ComboBox類來解決此問題,該類重寫OnItemsChanged ,保存當前的SelectedItem ,調用base.OnItemsChanged ,然后重置SelectedItem 如果不希望從有效=> null => valid的SelectedItem過渡,則可能需要在模型中傳播“ InhibitEvents”標志。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM