简体   繁体   中英

WPF Binding to dictionary with x:Name as a key

Please correct my question if it's not clear. What I'm looking for is..

Here's a sample binding for a dictionary... it works:

<TextBlock Text="{Binding Path=MyDictionary[ThisIsKeyInMyDict]}" />

I'm looking for:

<TextBlock x:Name="Id" Text="{Binding Path=MyDictionary[x:Name]}" />

You see? I want to look in dictionary for a key, the same as "Name" of this control.

Thanks for help!

You can use a MultiBinding for it:

   <Window.Resources>
        <local:DictValueConverter x:Key="dictValCnv"/>        
    </Window.Resources>
<TextBlock.Text>
    <MultiBinding Converter="{StaticResource dictValCnv}">
        <Binding Path="MyDictionary"/>
        <Binding RelativeSource="{RelativeSource Self}" Path="Name"/>
    </MultiBinding>
</TextBlock.Text>


using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
public class DictValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values==null || values.Length<2 )
        {
            return false;
        }

        var dict = values[0] as IDictionary;
        if(dict.Contains(values[1]))
    {
        return dict[values[1]];
    }
        return "KeyNotFound";
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM