如何将字典静态数据绑定为字典键?
我的XAML代码:
<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" />
词典键的静态数据类:
public static class DataNames
{
public static string SomeDataName { get; } = "some_data_name";
...
}
如何在XAML代码中将DataNames.SomeDataName
绑定为我的字典的键?
我使用字典转换器然后将其绑定为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}}"
感谢mm8帮助解决问题。他的答案包含字典转换器的代码。
答案 0 :(得分:1)
我担心XAML不支持这种“动态”绑定路径。
您可以使用转换器,例如:
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}}" />
答案 1 :(得分:0)
您可以使用静态标记扩展名:
<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" />