Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将枚举对象绑定到按钮的背景?_C#_Wpf_Dictionary_Binding_Background Color - Fatal编程技术网

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

C# 如何将枚举对象绑定到按钮的背景?,c#,wpf,dictionary,binding,background-color,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=...

我想将按钮的背景色绑定到枚举。我想知道是否有一个枚举对象可以保存多个值,例如状态和颜色。我希望避免两个可能不同步的枚举。这里有两个我想相互集成的枚举

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 }
};
公共词典stateValueColor=
新字典()
{
{StateValue.Player,Colors.Red},
{StateValue.Wall,Colors.Grey},
{StateValue.Box,Colors.Brown}
};

我建议您为此使用自定义转换器,并且仅从代码隐藏(或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%正确,但您应该明白。

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

谢谢Femaref!但是我得到了错误CS0077,它指出:
as”操作符可以用于任何*nullable*类型,即引用和nullable类型。
。具体来说,cast
StateValue sv=(值为StateValue),因为StateValue是枚举。枚举不能为
null
。这就是错误发生的原因。您的类型检查很好,但对转换问题没有帮助。此外,为了测试,我返回颜色值resp。枚举值已硬编码。这不会改变我的按钮背景色。相反,它会释放默认的背景色。