WPF binding textbox to dictionary entry
There is a Binding error in your code because MyDict
is not a property. You have to bind to a Property
and not to a 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 the MyDict Field
to a Property
like shown 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 variants will not work as MyDict["key"] returns a string
and string
does not have a Text
or Value
property. The other two variants should work.
Text="{Binding MyDict[First].Text}"Text="{Binding MyDict[First].Value}"
The following bindings will work
Text="{Binding MyDict[First]}"Text="{Binding Path=MyDict[First]}"