How to bind a (static) Dictionary to Labels?

邮差的信 提交于 2019-12-19 20:23:33

问题


I have a static Dictionary

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

This Dictionary contains Data i want to show in a Grid-Control:

<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.) i dont know how to get access (in xaml) to the dictionary

2.) i want to bind the Value of a specified key to the Content-Property of the Label.

how to do this?


回答1:


You need to use a converter which will allow you to extract your value out of the Dictionary via the ConverterParameter.

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];
    }
}

The XAML would be as follows...

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

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



回答2:


To get access to the Dictionary, you have to do something like this (if your DataContext isn't already an instance of X):

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

To access the values in the dictionary, your binding has to look as follows:

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



回答3:


Your binding will need to change to be the following:

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

If you look at Binding Paths from the MSDN, you will see that string indexers can be specified in XAML. local will be the xmlns representing the namespace X resides in.




回答4:


I voted up Aaron for the converter and Tobias for indexers, but to actually access the static dictionary, try duplicating the property at the instance level and binding to that

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

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


来源:https://stackoverflow.com/questions/8759153/how-to-bind-a-static-dictionary-to-labels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!