WPF binding a text field to a dictionary entry

I am trying to bind a wpf text field to a dictionary placed in the viewmodel. The viewmodel is used as the datacontext for the view. I found a lot of examples, and it sounds simple, but it will not work for me.

View:

TextBox x: Name = "txbTest" Grid.Row = "10" Grid.Column = "2" Text = "{Binding MyDict [First]}"

ViewModel:

public Dictionary<string, string> MyDict = new Dictionary<string, string> { {"First", "Test1"}, {"Second", "Test2"} }; 

I try all the options that I found

 Text="{Binding MyDict[First]}" Text="{Binding Path=MyDict[First]}" Text="{Binding MyDict[First].Text}" Text="{Binding MyDict[First].Value}" 

But nothing works, the text box is empty. Any idea?

+7
dictionary wpf binding
source share
1 answer

There is a binding error in the code because MyDict not a property. You must bind to Property , not Field

 System.Windows.Data Error: 40 : BindingExpression path error: 'MyDict' property not found on 'object' ''MainWindow' (Name='')'. BindingExpression:Path=MyDict[First]; DataItem='MainWindow' (Name=''); target element is 'TextBox' (Name='textBox1'); target property is 'Text' (type 'String') 

Change MyDict Field to Property as below

  private Dictionary<string, string> _MyDict; public Dictionary<string, string> MyDict { get { return _MyDict; } set { _MyDict = value; } } 

In the constructor of your ViewModel initialize MyDict.

  MyDict = new Dictionary<string, string> { {"First", "Test1"}, {"Second", "Test2"} }; 

The following two options will not work, since MyDict ["key"] returns string and string does not have the Text or Value property. The other two options should work.

 Text="{Binding MyDict[First].Text}" Text="{Binding MyDict[First].Value}" 
+18
source share

All Articles