【问题标题】:wpf dictionary binding where key=variablewpf 字典绑定,其中 key=variable
【发布时间】:2012-12-10 11:05:24
【问题描述】:

我有一本测试词典

MyDict = new Dictionary<string, Uri>
{
    {"First", new Uri("alma.jpg", UriKind.Relative)},
    {"Second", new Uri("korte.jpg", UriKind.Relative)}
};

还有一个简单的 XAML

<TextBlock Text="{Binding MyDict[First]}"
           FontSize="13" Width="200" Height="30" />

这完美地展示了第一个关键元素的价值

我想要的是 我有一个字符串变量:DictKey 让 DictKey="First"

如何重写 XAML 以使用此变量

<TextBlock Text="{Binding MyDict[???DictKey????]}"
           FontSize="13" Width="200" Height="30" />

谢谢。

【问题讨论】:

  • 如何格式化代码块请看here

标签: wpf binding dictionary


【解决方案1】:

我假设你有一些属性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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2012-09-26
    • 2023-04-01
    • 2011-03-27
    相关资源
    最近更新 更多