How to associate a (static) dictionary with shortcuts?

I have a static dictionary

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

This dictionary contains the data I want to show in Grid-Control mode:

 <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 do not know how to access (in xaml) the dictionary

2.) I want to bind the value of the specified key to the Content-Property of the label.

how to do it?

+4
source share
4 answers

You need to use converter , which will allow you to extract your value from Dictionary through 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]; } } 

XAML will look like this:

 <Window.Resources> <converters:DictConverter x:Key="MyDictConverter"/> </Window.Resources> Content="{Binding MyDictProperty, Converter={StaticResource MyDictConverter}, ConverterParameter=foo}" 
+3
source

To access the dictionary, you should do something like this (if your DataContext is not 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 should look like this:

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

Your binding should change as follows:

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

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

+4
source

I voted for Aaron for the converter and Tobias for the indexers, but in order to actually access the static dictionary, try duplicating the property at the instance level and bind to it

 // Code class X { protected static Dictionary<string,string> StaticDict { get { ... } } public Dictionary<string, string> InstanceDict { get { return StaticDict; } } } // Xaml Content="{Binding InstanceDict, Converter = ... } " 
0
source

Source: https://habr.com/ru/post/1389659/


All Articles