I have a static Dictionary
class X { static Dictionary MyDict {get { ... }} }
This Dictionary contains Data i want to
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.
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 = ... } "
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]}" />
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}"