ReactiveBinding:使用not(!)运算符绑定数据时出错

本文关键字:绑定 运算符 数据 出错 使用 not ReactiveBinding | 更新日期: 2023-09-27 18:26:20

我正试图使用ReactiveUI版本6.5.0.0中的IReactiveBinding将视图模型中的字段绑定到控件的属性。

我想将视图模型中的否定值绑定到控件的属性:

this.Bind(ViewModel, vm => !vm.IsSmth, control => _checkBoxSmth.Enabled, _checkBoxSmth.Events().CheckStateChanged)

但我只是得到了这个错误,找不到如何修复它。

System.NotSupportedException: Unsupported expression type: 'Not' caught here:

有什么建议吗?

ReactiveBinding:使用not(!)运算符绑定数据时出错

问题的根源在于Bind只允许vmPropertyviewProperty参数中的属性,而不能通过函数调用来更改它们。如果你不想改变你的视图模型,你可以使用Bind重载,它接受IBindingTypeConverter,这将简单地否定你的布尔值。以下是BooleanToVisibilityTypeConverter实现的示例。

你的代码可能看起来像这样(注意-我没有测试它):

public class NegatingTypeConverter : IBindingTypeConverter
{
    public int GetAffinityForObjects(Type fromType, Type toType)
    {
        if (fromType == typeof (bool) && toType == typeof (bool)) return 10;
        return 0;
    }
    public bool TryConvert(object from, Type toType, object conversionHint, out object result)
    {
        result = null;
        if (from is bool && toType == typeof (bool))
        {
            result = !(bool) from;
            return true;
        }
        return false;
    }
}

请注意,如果使用OneWayBind,则不需要实现自己的转换器,因为存在接受函数更改视图模型属性的重载(请查找selector参数)。

我的建议是添加一个负字段并绑定到该字段
这里有一个非常简单的概念示例。

public class Model
{
    public bool IsSmth { get; set; }
    public bool IsNotSmth 
    { 
        get { return !IsSmth; }
        set { IsSmth = value; }
    }
}

然后像这样绑起来。

this.Bind(ViewModel, vm => vm.IsNotSmth, control => _checkBoxSmth.Enabled, _checkBoxSmth.Events().CheckStateChanged)