How to bind to a dictionary element with a change notification?

Consider the following XAML:

<Window x:Class="WpfApplication1.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> <TextBlock Text="{Binding Dic[foo]}" /> <Button Content="test" Click="Button_Click" /> </StackPanel> </Window> 

And Code:

 namespace WpfApplication1 { public partial class MainWindow : Window { public Dictionary<string, string> Dic { get; set; } public MainWindow() { InitializeComponent(); Dic = new Dictionary<string, string>(); Dic.Add("foo", "bar"); DataContext = this; } private void Button_Click(object sender, RoutedEventArgs e) { // Doesn't work :( Dic["foo"] = "YEAH!"; } } } 

Here, the TextBlock correctly bound to the dictionary element "foo". But how to make it update when its value changes?

0
source share
3 answers

You need to raise a notification of an indexer change using Binding.IndexerName as the property name, you might want to encapsulate this in a new Dictionary inheritance or control class.

0
source

you have dictionnary to be dictionnary (from string, DescriptionObject), where DescriptionObject has a notification property for the string, implements PropertyChanged, and has a ToString override.
Then you add (foo, fooDescription) to your dictionary. If you change the fooDescription in the ButtonClick handler, the TextBlock will also change.

0
source

You need to add an indexer to your code:

 private Dictionary<string, string> Dic { get; set; } public string this[string key] { get { return Dic[key]; } set { if(key != null && Dic[key] != value) Dic[key] = value; OnPropertyChanged("Item[" + key + "]"); } } 

Then in xaml you do the binding to the index, and when the element changes, it will notify:

 <Window x:Class="WpfApplication1.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> <TextBlock Text="{Binding [foo]}" /> <Button Content="test" Click="Button_Click" /> </StackPanel> </Window> 
0
source

All Articles