Two Way Data Binding With a Dictionary in WPF

前端 未结 5 1401
天涯浪人
天涯浪人 2020-12-05 07:37

I\'d like to bind a Dictionary to a ListView in WPF. I\'d like to do this in such a way that the Values in the

5条回答
  •  眼角桃花
    2020-12-05 07:55

    I don't think you're going to be able to do what you'd like with a dictionary.

    1. Because the Dictionary doesn't implement INotifyPropertyChanged or INotifyCollectionChanged
    2. Because it's not going to allow two way binding like you want.

    I'm not sure if it fits your requirements exactly, but I would use an ObservableCollection, and a custom class.

    I'm using a DataTemplate, to show how to make the binding on the values two way.

    Of course in this implementation Key isn't used, so you could just use an ObservableCollection

    Custom Class

    public class MyCustomClass
    {
        public string Key { get; set; }
        public int Value { get; set; }
    }
    

    Set ItemsSource

    ObservableCollection dict = new ObservableCollection();
    dict.Add(new MyCustomClass{Key = "test", Value = 1});
    dict.Add(new MyCustomClass{ Key = "test2", Value = 2 });
    listView.ItemsSource = dict;
    

    XAML

    
        
            
        
    
    
        
            
                
            
        
    
    

提交回复
热议问题