WPF Binding to dictionary with x:Name as a key

前端 未结 1 949
再見小時候
再見小時候 2021-01-23 16:05

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:



        
相关标签:
1条回答
  • 2021-01-23 16:30

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题