Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF binding textbox to dictionary entry

i try to bind a wpf textbox to a dictionary placed in a viewmodel. The viewmodel is used as 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 variants i found

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

But nothing works, textbox is empty. Any idea?

like image 300
user2377283 Avatar asked Aug 09 '13 06:08

user2377283


1 Answers

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]}"
like image 59
Anand Murali Avatar answered Sep 20 '22 02:09

Anand Murali