[英]WPF Binding to dictionary with x:Name as a key
Please correct my question if it's not clear. 如果不清楚,请更正我的问题。 What I'm looking for is..
我正在寻找的是..
Here's a sample binding for a dictionary... it works: 这是字典的示例绑定...它可以工作:
<TextBlock Text="{Binding Path=MyDictionary[ThisIsKeyInMyDict]}" />
I'm looking for: 我在找:
<TextBlock x:Name="Id" Text="{Binding Path=MyDictionary[x:Name]}" />
You see? 你看? I want to look in dictionary for a key, the same as "Name" of this control.
我想在字典中查找与该控件的“名称”相同的键。
Thanks for help! 感谢帮助!
You can use a MultiBinding for it: 您可以为其使用MultiBinding:
<Window.Resources>
<local:DictValueConverter x:Key="dictValCnv"/>
</Window.Resources>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource dictValCnv}">
<Binding Path="MyDictionary"/>
<Binding RelativeSource="{RelativeSource Self}" Path="Name"/>
</MultiBinding>
</TextBlock.Text>
using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
public class DictValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values==null || values.Length<2 )
{
return false;
}
var dict = values[0] as IDictionary;
if(dict.Contains(values[1]))
{
return dict[values[1]];
}
return "KeyNotFound";
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.