我假设你有一些财产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>
转换器使用这两个值从字典中读取项目:
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();
}
}