wpf dictionary binding where key=variable

后端 未结 1 1681
情话喂你
情话喂你 2020-12-11 07:18

I have a test dictionary

MyDict = new Dictionary
{
    {\"First\", new Uri(\"alma.jpg\", UriKind.Relative)},
    {\"Second\", new Uri(\"ko         


        
相关标签:
1条回答
  • 2020-12-11 08:19

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