0

Consider 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 Backing 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 TextBlock properly binds to dictionary item "foo". But how to make it to update when its value is changed?

Poma
  • 8,174
  • 18
  • 82
  • 144

3 Answers3

0

You need to add indexer to your code like that:

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 the xaml you make binding to the indexer, and when the item change it will be 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>
Ramzy Abourafeh
  • 1,195
  • 7
  • 17
  • 35
0

You need to raise a change notification for the indexer using Binding.IndexerName as property name, you might want to encapsulate that in a new class inheriting or managing Dictionary.

H.B.
  • 166,899
  • 29
  • 327
  • 400
0

have your dictionnary be a dictionnary(of string, DescriptionObject) Where DescriptionObject has a notifying string property, implements PropertyChanged and has a ToString override.
Then you add (foo, fooDescription) to your dictionnary. If you change fooDescription in your ButtonClick handler, the TextBlock will change too.

GameAlchemist
  • 18,995
  • 7
  • 36
  • 59