簡體   English   中英

WPF以x:Name為鍵綁定到字典

[英]WPF Binding to dictionary with x:Name as a key

如果不清楚,請更正我的問題。 我正在尋找的是..

這是字典的示例綁定...它可以工作:

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

我在找:

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

你看? 我想在字典中查找與該控件的“名稱”相同的鍵。

感謝幫助!

您可以為其使用MultiBinding:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM