WPF Single selection between two ListBoxes

后端 未结 1 698
小蘑菇
小蘑菇 2021-02-15 01:28

I\'m having the following problem: I have two ListBox, with two different ItemSource, but both of them have the same binding for the

1条回答
  •  梦如初夏
    2021-02-15 02:16

    Try using SelectedValue instead, this will sop the behaviour you are seeing

     
    

    It seems that SelectedItem does not deselect is the selected item is not found in the list, But SelectedValue does seem to deselect it, not sure why

    You can see the diffence in this sample app:

    xaml:

    
        
            
            
                
                
            
            
            
                
                
            
        
    
    

    code:

    public partial class MainWindow : Window , INotifyPropertyChanged
    {
        private CustomObject _mySelectedItem;
        private CustomObject _mySelectedValue;
        private ObservableCollection _items = new ObservableCollection();
        private ObservableCollection _items2 = new ObservableCollection();
    
        public MainWindow()
        {
            InitializeComponent();
            MyItemSource1.Add(new CustomObject { Name = "Stack" });
            MyItemSource1.Add(new CustomObject { Name = "Overflow" });
            MyItemSource2.Add(new CustomObject { Name = "Stack" });
            MyItemSource2.Add(new CustomObject { Name = "Overflow" });
        }
    
        public ObservableCollection MyItemSource1
        {
            get { return _items; }
            set { _items = value; }
        }
    
        public ObservableCollection MyItemSource2
        {
            get { return _items2; }
            set { _items2 = value; }
        }
    
        public CustomObject MySelectedItem
        {
            get { return _mySelectedItem; }
            set { _mySelectedItem = value; NotifyPropertyChanged("MySelectedItem"); }
        }
    
        public CustomObject MySelectedValue
        {
            get { return _mySelectedValue; }
            set { _mySelectedValue = value; NotifyPropertyChanged("MySelectedValue"); }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }
    
    public class CustomObject
    {
        public string Name { get; set; }
        public override string ToString()
        {
            return Name;
        }
    }
    

    enter image description here

    0 讨论(0)
提交回复
热议问题