如果存在,我如何绑定到字典中的键

时间:2015-03-20 14:53:00

标签: wpf dictionary mvvm binding

我有一个案例,我不知道字典中是否存在密钥,但如果确实存在。我想绑定它。

在这种情况下,它是一种颜色,所以我使用转换器来转换颜色和绑定。这很有效,但只有在密钥存在的情况下才能运行!

我想不出一种设置触发器的方法,在执行绑定之前检查键是否存在?

请注意,在下面的代码中,fieldColour可能存在也可能不存在。我想设置一个我可以做的数据触发器,但我不知道这是怎么回事。

<ToggleButton.Style>
  <Style>
    <Setter Property="ToggleButton.Background" Value="{Binding Path=Schema.KeyValues[fieldColour], Converter={converters:Converter_StringToColour}}" />
  </Style>
</ToggleButton.Style>

1 个答案:

答案 0 :(得分:0)

我最终找到了最好的方法。您可以将它传递给转换器,然后决定参数是否为null:

C#

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (parameter == null) return null;
    if (value == null) return null;

    string key = (parameter as string).ToLower();
    Dictionary<string, string> dict = value as Dictionary<string, string>;
    if (!dict.ContainsKey(key)) return null;
    string colour = dict[key];

    var converter = TypeDescriptor.GetConverter(typeof(Color));
    if (converter.IsValid(colour))
    {
        //Easter Egg.
        if (colour == "Magenta")
        {
            ErrorConsoleViewModel.Instance.LogWarning("Magenta? Really? Are you trying to blind me!");
        }

        Color newCol = (Color)converter.ConvertFromString(colour);
        return new SolidColorBrush(newCol);
    }
    ErrorConsoleViewModel.Instance.LogWarning("Colour " + colour + " not found. See C# Colour Table: http://www.dotnetperls.com/color-table");

    return null;
}

XAML

                    <Style>
                        <Setter Property="ToggleButton.Background" Value="{Binding Path=Schema.KeyValues, Converter={converters:Converter_DictionaryStringToColour}, ConverterParameter='fieldColour'}" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=Schema.KeyValues, Converter={converters:Converter_DictionaryStringToColour}, ConverterParameter='fieldColour'}" Value="{x:Null}">
                                <Setter Property="ToggleButton.Background" Value="#A9C7F0" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
相关问题