wpf 字典绑定,其中 key=variable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13799705/
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
wpf dictionary binding where key=variable
提问by KusziWorks
I have a test dictionary
我有一本测试字典
MyDict = new Dictionary<string, Uri>
{
{"First", new Uri("alma.jpg", UriKind.Relative)},
{"Second", new Uri("korte.jpg", UriKind.Relative)}
};
and a simple XAML
和一个简单的 XAML
<TextBlock Text="{Binding MyDict[First]}"
FontSize="13" Width="200" Height="30" />
That shows perfectly the First key element Value
这完美地显示了第一个关键元素值
What I want is I have a string variable: DictKey Lets DictKey="First"
我想要的是我有一个字符串变量:DictKey Lets DictKey="First"
How to rewrite the XAML to use this variable
如何重写 XAML 以使用此变量
<TextBlock Text="{Binding MyDict[???DictKey????]}"
FontSize="13" Width="200" Height="30" />
thx.
谢谢。
回答by Lubo
I assume you have some property DictKeywhich holds the key of the item.
You can use MultiBindingand set the first binding to your dictionary property and second binding to the property with the key of the item:
我假设您有一些DictKey保存项目键的属性。您可以使用MultiBinding并将第一个绑定设置为您的字典属性,并使用项目的键将第二个绑定设置为该属性:
<TextBlock FontSize="13" Width="200" Height="30">
<TextBlock.Text>
<MultiBinding>
<MultiBinding.Converter>
<local:DictionaryItemConverter/>
</MultiBinding.Converter>
<Binding Path="MyDict"/>
<Binding Path="DictKey"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
The converter uses both values to read the item from dictionary:
转换器使用这两个值从字典中读取项目:
public class DictionaryItemConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values != null && values.Length >= 2)
{
var myDict = values[0] as IDictionary;
var myKey = values[1] as string;
if (myDict != null && myKey != null)
{
//the automatic conversion from Uri to string doesn't work
//return myDict[myKey];
return myDict[myKey].ToString();
}
}
return Binding.DoNothing;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}

