Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

wpf dictionary binding where key=variable

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

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

How to rewrite the XAML to use this variable

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

thx.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...