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

JJD*_*JJD 2 c# wpf binding dictionary background-color

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

enum StateValue { Player, Wall, Box }
enum StateColor { Colors.Red, Colors.Grey, Colors.Brown }
Run Code Online (Sandbox Code Playgroud)

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

<Button Content="Player" Background="{Binding Source=...?}" />
Run Code Online (Sandbox Code Playgroud)

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

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

Fem*_*ref 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
    }
}
Run Code Online (Sandbox Code Playgroud)

在wpf中:

<Button 
  Content="Player" 
  Background="{Binding Source=StateValue, 
    Converter={StaticResource stateValueColorConverter}}" />
Run Code Online (Sandbox Code Playgroud)

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

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