WPF 将文本框绑定到字典条目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18141527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:24:17  来源:igfitidea点击:

WPF binding textbox to dictionary entry

wpfbindingdictionary

提问by user2377283

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.

我尝试将 wpf 文本框绑定到放置在视图模型中的字典。视图模型用作视图的数据上下文。我找到了很多例子,听起来很简单,但它对我不起作用。

View:

看法:

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

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?

但没有任何效果,文本框是空的。任何的想法?

回答by Anand Murali

There is a Binding error in your code because MyDictis not a property. You have to bind to a Propertyand not to a Field

您的代码中存在绑定错误,因为MyDict它不是属性。你必须绑定到 aProperty而不是 aField

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 Fieldto a Propertylike shown below

改变MyDictFieldProperty像下面所示

    private Dictionary<string, string> _MyDict;

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

In the constructor of your ViewModelinitialize MyDict.

ViewModel初始化 MyDict的构造函数中。

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

The following two variants will not work as MyDict["key"] returns a stringand stringdoes not have a Textor Valueproperty. The other two variants should work.

以下两个变体将不起作用,因为 MyDict["key"] 返回 astring并且string没有 a TextorValue属性。其他两个变体应该可以工作。

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

The following bindings will work

以下绑定将起作用

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