wpf 字典绑定(bind),其中 key=variable

标签 wpf binding dictionary

我有一本测试词典

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" />

谢谢。

最佳答案

我假设你有一些属性(property)DictKey它持有项目的关键。
您可以使用 MultiBinding并将第一个绑定(bind)设置为您的字典属性,并将第二个绑定(bind)设置为具有项目键的属性:

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

关于wpf 字典绑定(bind),其中 key=variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13799705/

相关文章:

c# - Caliburn.Micro,来自 UserControl 和 Conductor.OneActive 的多个 ActiveItem

wpf - 如何在 WPF 中将组合框的样式更改为标签或超链接?

c# - 向WPF Prism MVVM应用程序添加后台线程

Python 类绑定(bind)不起作用,引发错误

javascript - 在javascript中的字典数组中搜索一个id

c# - WPF 调度程序 {"The calling thread cannot access this object because a different thread owns it."}

javascript - 将更改事件添加/委托(delegate)/绑定(bind)到 Chosen 插件?

wpf - 从代码隐藏添加转换器到页面资源

python : How to call dictionnary-contained callables at a given time?

英语中所有单词及其频率的词典