似乎无法让我的IValueConverter工作

时间:2015-07-03 19:42:47

标签: c# wpf mvvm ivalueconverter

拥有以下简单的xaml

<UserControl.Resources>
        <converters:StateToColorConverter x:Key="stateToColorConverter"/>
</UserControl.Resources>
<StackPanel>
    <Grid Width="150" Height="100" Background="{Binding State, Converter={StaticResource stateToColorConverter}}"></Grid>
    <Button 
        Width="100" 
        Height="70"
        Command="{Binding InitializeCommand}">Initialize</Button>
</StackPanel>

它的视图模型有一个属性State,它具有正确的值。

public class MachineControlViewModel :ViewModelBase
{
    private readonly IMachine machine;

    public RelayCommand InitializeCommand { get; set; }

    private MachineStates state;
    public MachineStates State
    {
        get { return state; }
        set { Set(() => State, ref state, value); }
    }

    public MachineControlViewModel(IMachine machine)
    {
        this.machine = machine;

        InitializeCommand = new RelayCommand(Initialize, CanInitialize);

        State = machine.State;

        machine.StateChanged += MachineOnStateChanged;
    }
    // left out irrelevant parts
}

然后,IValueConverter实现

public class StateToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var state = (MachineStates) Enum.Parse(typeof (MachineStates), value.ToString());

        switch (state)
        {
            case MachineStates.Idle:
                return Color.Red;
            case MachineStates.Initialized:
                return Color.Green;
            case MachineStates.Production:
                return Color.Blue;
            case MachineStates.Error:
                return Color.Red;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

当我运行我的应用程序时,网格的背景颜色将不会显示。

当我设置BackColor硬编码时(所以没有值转换器),它可以正确显示。

当我使用我的值转换器,并在转换方法中放置一个断点时,我可以看到代码执行得很好,并且返回了一个Color。但没有显示任何内容......

我做错了什么?

2 个答案:

答案 0 :(得分:1)

转换器应返回Brush,而不是Color,因为这是Background属性的类型。

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

    switch ((MachineStates)value)
    {
        case MachineStates.Idle:
            brush = Brushes.Red;
            break;
        case MachineStates.Initialized:
            brush = Brushes.Green;
            break;
        case MachineStates.Production:
            brush = Brushes.Blue;
            break;
        case MachineStates.Error:
            brush = Brushes.Red;
            break;
        default:
            break;
    }

    return brush;
}

它应该特别不返回System.Drawing.Color(就像你做的那样),因为那是WinForms,而不是WPF。

答案 1 :(得分:1)

背景是Brush类型。将转换器更改为此

 return new SolidColorBrush(Colors.Red);

Background property