如何将枚举对象绑定到按钮的背景?

时间:2010-11-09 00:01:03

标签: c# wpf dictionary binding background-color

我想将按钮的背景颜色绑定到枚举。我想知道是否有一个可以容纳多个值的枚举对象,例如状态和颜色。我想避免两个可能不同步的枚举。以下是我想要相互整合的两个枚举。

enum StateValue { Player, Wall, Box }
enum StateColor { Colors.Red, Colors.Grey, Colors.Brown }

然后我需要为XAML按钮创建一个绑定。

<Button Content="Player" Background="{Binding Source=...?}" />

也许,像下面这样的字典很有帮助。但我仍然不知道如何编写绑定。

public Dictionary<StateValue, Color> stateValueColor = 
new Dictionary<ElementState, Color>()
{
 { StateValue.Player, Colors.Red },
 { StateValue.Wall, Colors.Grey },
 { StateValue.Box, Colors.Brown }
};

2 个答案:

答案 0 :(得分:6)

我建议您使用自定义转换器,并仅从代码隐藏(或ViewModel)提供枚举。

这看起来像这样:

[ValueConversion(typeof(StateValue), typeof(Color))]
public class StateValueColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(!(value is StateValue))
            throw new ArgumentException("value not of type StateValue");
        StateValue sv = (StateValue)value;
        //sanity checks
        switch (sv)
            {
                case StateValue.Player:
                return Colors.Red;
                //etc
            }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
       Color c = (value as Color);
       if(c == Colors.Red)
         return StateValue.Player;
       //etc
    }
}

在wpf中:

<Button 
  Content="Player" 
  Background="{Binding Source=StateValue, 
    Converter={StaticResource stateValueColorConverter}}" />

当然,如果你正在使用DI容器,你可以提供不同的接口实现,改变颜色,只需让你的视图注入转换器,并通过绑定到绑定的转换器属性提供。

注意:这段代码是在没有编译器的情况下编写的,我不确定xaml是否100%正确,但你应该明白这一点。

答案 1 :(得分:0)

要返回正确的类型,需要在return new SolidColorBrush(Colors.Red);中编写StateValueColorConverter。这解决了背景颜色丢失的问题。