转换器不能应用于需要 IValueConverter 类型的 属性

Converter cannot be applied to a property that expects the type IValueConverter

我有一个实现 IValueConverter 但不能绑定到 属性 的转换器。

public class StatusToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Brushes.Red;
    }

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

}

在 XAML 中,我将转换器添加为资源并将绑定添加到元素

<UserControl.Resources>
    <Converters:StatusToBrushConverter x:Key="StatusConverter"/>
</UserControl.Resources>            

<Rectangle Fill="{Binding Status, Converter={StaticResource StatusConverter}, ElementName=userControl}"/>

但我经常收到错误

An object of the type "StatusToBrushConverter" cannot be applied to a property that expects the type "System.Windows.Data.IValueConverter"

但是转换器实现了接口 IValueConverter。我尝试了几件事:

以前编写的转换器可以工作。想法?

作为转换器的替代方法,可以在 VM 上创建关联的通知 属性 以提供相关颜色。

例如,假设您的颜色实际上与另一个名为 IsValid 的通知 属性 不同。当 IsValid 改变时,它应该改变矩形上的颜色。

 private bool _isValid;

 public bool IsValid
 {
     get { return _IsValid; }
     set 
     {
         _isValid = value;
         NotifyPropertyChanged("IsValid");
         NotifyPropertyChanged("UserStatusColor");
     }
 }


 public Brush UserStatusColor
 {
     get { return IsValid ? Brushes.Green : Brushes.Red; }
 }

....

<Rectangle Fill="{Binding UserStatusColor}"/>

因此无需特洛伊木马程序即可更改颜色。

在您的 xaml 文件中设置您之前编写的工作转换器以查看问题是否仍然存在,并将问题隔离到 xaml(或您编写的转换器)。

确保您的 StatusToBrushConverter class 通过使用其完全限定的命名确实实现了正确的 IValueConverter 接口:

public class StatusToBrushConverter : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Brushes.Red;
    }

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

您也可以尝试暂时使用 属性 元素语法进行调试:

<Rectangle>
    <Rectangle.Fill>
        <Binding Path="Status" ElementName="userControl">
            <Binding.Converter>
                <local:StatusToBrushConverter />
            </Binding.Converter>
        </Binding>
    </Rectangle.Fill>
</Rectangle>

解决方案如下:转换器位于 class 库中。应该不是问题,对于其他转换器也没有问题。但是我在 WPF 项目中移动了转换器,现在它可以工作了。我没有更改转换器中的任何内容。

今天早上打开电脑时,带有错误消息的初始错误消失了。 visual studio 的几次重新启动是不够的。只是 PC 重启就成功了。

感谢您的建议。我都试过了。