问题
How to bind dictionary static data as dictionary key?
My XAML code:
<TextBlock
x:Name="AxisXTextBlock"
Width="37"
Height="18"
Margin="106,19,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
FontFamily="Source Code Pro"
Text="{Binding DataStructure.DictionaryOfValuesReadOnly[AXIS_X].IntValue, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
TextWrapping="Wrap" />
Class of static data for keys of dictionaries:
public static class DataNames
{
public static string SomeDataName { get; } = "some_data_name";
...
}
How can I bind DataNames.SomeDataName
as a key of my dictionary in XAML code?
UPDATE
I use dictionary converter and then bind it as StaticResource
xmlns:converters="clr-namespace:AppName.Converters"
...
<converters:SomeConverter x:Key="SomeConverter " />
...
Text="{Binding Path=DataStructure, Converter={StaticResource SomeConverter}, ConverterParameter={x:Static data:DataNames.SomeDataName}}"
Thanks mm8 for helping in solution. His answer contains code for dictionary converter.
回答1:
I am afraid XAML doesn't support this kind of "dynamic" binding paths.
You could use a converter though, e.g.:
public class DictConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
IDictionary<string, string> dict = value as IDictionary<string, string>;
string key = parameter as string;
string s;
if (dict != null && !string.IsNullOrEmpty(key) && dict.TryGetValue(key, out s))
return s;
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
<TextBlock Text="{Binding Path=Dict, Converter={StaticResource conv}, ConverterParameter={x:Static local:DataNames.AxisX}}" />
回答2:
You can use static markup extension:
<TextBlock
x:Name="AxisXTextBlock"
Background="Yellow"
Width="100"
Height="30"
Margin="106,19,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
FontFamily="Source Code Pro"
Text="{Binding DataStructure.DictionaryOfValuesReadOnly[{x:Static local:DataNames.AxisX}].IntValue, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
TextWrapping="Wrap" />
来源:https://stackoverflow.com/questions/44111331/bind-static-data-as-dictionary-key