简体   繁体   English

WPF / XAML:绑定到字典 <object, object> 按键输入

[英]WPF/XAML: Binding to Dictionary<object, object> entry by key

I am programming a MVVM-application and in the ViewModel I created a property of the type Dictionary<Geschäftsjahr, object> . 我正在编写MVVM应用程序,并在ViewModel中创建了Dictionary<Geschäftsjahr, object>类型的属性。

The Geschäftsjahr -object has 2 properties and holds two different years (fe: 2017/18). Geschäftsjahr具有2个属性,并拥有两个不同的年份(fe:2017/18)。 The ToString()-Method returns the data in exactly this format. ToString()-Method完全以这种格式返回数据。

Now I want to bind a certain entry of the dictionary with XAML to a TextBox. 现在,我想将字典的某个条目与XAML绑定到TextBox。 Is it possible, to access the dictionary in the following way: 是否可以通过以下方式访问字典:

<TextBox Text={Binding Path=ViewModelProperty[2017/18]} ... /> 

It's very important to access the dictionary over the key. 通过密钥访问字典非常重要。 Actually it doesn't work this way... 其实这种方式行不通...

Thanks, Nicolas 谢谢,尼古拉斯

Instead of overriding the ToString() method of the class, create a new property that returns the formatted dates. 而不是重写类的ToString()方法,而是创建一个返回格式化日期的新属性。 Please see below. 请看下面。

New property that returns the correct formatted dates : 返回正确格式日期的新属性:

public string DatesDisplayText => "(Do your formatting here)";

Then your xaml can look like this : 然后,您的xaml可能如下所示:

<TextBox Text={Binding Path=ViewModelProperty[Key].DatesDisplayText} ... />

Is it possible, to access the dictionary in the following way ...? 是否可以通过以下方式访问字典...?

Only if the key of the dictionary is a compile-time constant like for example the int 1 or the string "abc". 仅当字典的键是编译时常量 (例如int 1string “ abc”)时。

It's not possible if the key is a Geschäftsjahr . 如果密钥是Geschäftsjahr是不可能的。 Then you would better bind to a property that performs the lookup for you, eg: 然后,最好将其绑定到为您执行查找的属性,例如:

public string Text => ViewModelProperty[new Geschäftsjahr(2017, 2018)];

XAML: XAML:

<TextBlock Text="{Binding Text}" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM