Bind static data as dictionary key

筅森魡賤 提交于 2020-01-30 11:31:08

问题


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

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