WPF字典结合,其中的关键变量= [英] wpf dictionary binding where key=variable

查看:85
本文介绍了WPF字典结合,其中的关键变量=的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试字典

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

和一个简单的XAML

and a simple XAML

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

这显示了完美的第一要素值

That shows perfectly the First key element Value

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

What I want is I have a string variable: DictKey Lets DictKey="First"

如何改写XAML使用这个变量

How to rewrite the XAML to use this variable

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

THX。

推荐答案

我假定你有一些财产 DictKey 持有该项目的关键。
您可以使用 MultiBinding ,并设置第一个绑定到你的字典财产和第二与该项目的键绑定的属性:

I assume you have some property DictKey which holds the key of the item. You can use MultiBinding and set the first binding to your dictionary property and second binding to the property with the key of the item:

<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();
    }
}

这篇关于WPF字典结合,其中的关键变量=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆