如何将(静态)字典绑定到标签?

时间:2012-01-06 14:14:46

标签: c# wpf binding dictionary

我有一个静态字典

class X { static Dictionary<string,string> MyDict {get { ... }} }

此词典包含我想在网格控件中显示的数据:

<Grid>
  <!-- Row and Column-Definitions here -->
  <Label Grid.Row="0" Grid.Column="0" Content="{Binding MyDict.Key=="foo" }" ToolTip="foo" />
  <!-- some more labels -->
</Grid>

1。)我不知道如何访问(在xaml中)字典

2。)我想将指定键的Value绑定到Label的Content-Property。

怎么做?

4 个答案:

答案 0 :(得分:4)

要访问Dictionary,您必须执行以下操作(如果您的DataContext不是X的实例):

<Grid>
    <Grid.DataContext>
        <X xmlns="clr-namespace:Your.Namespace" />
    </Grid.DataContext>
    <!-- other code here -->
</Grid>

要访问字典中的值,您的绑定必须如下所示:

<Label Content="{Binding MyDict[key]}" />

答案 1 :(得分:4)

您的绑定需要更改为以下内容:

Content="{Binding Path=[foo], Source={x:Static local:X.MyDict}}"

如果从MSDN查看Binding Paths,您会看到可以在XAML中指定字符串索引器。 local将是表示名称空间X所在的xmlns。

答案 2 :(得分:3)

您需要使用converter,以便通过DictionaryConverterParameter中提取您的价值。

public class DictConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Dictionary<string,string> data = (Dictionary<string,string>)value;
        String parameter = (String)parameter;
        return data[parameter];
    }
}

XAML如下......

<Window.Resources>
    <converters:DictConverter x:Key="MyDictConverter"/>
</Window.Resources>

Content="{Binding MyDictProperty, Converter={StaticResource MyDictConverter}, ConverterParameter=foo}"

答案 3 :(得分:0)

我投票给Aaron转换器和Tobias索引器,但实际访问静态字典,尝试在实例级复制属性并绑定到

// Code
class X 
{ 
    protected static Dictionary<string,string> StaticDict { get { ... } } 
    public Dictionary<string, string> InstanceDict { get { return StaticDict; } } 
} 

// Xaml
Content="{Binding InstanceDict, Converter = ... } "