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

ReactiveBinding: Error when binding data using not (!) operator

我正在尝试使用来自 ReactiveUIIReactiveBinding 将视图模型中的字段绑定到控件的 属性 ], 版本 6.5.0.0.

我想将取反值从视图模型绑定到控件的 属性:

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

但我刚收到这个错误,但找不到解决方法。

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

有什么建议吗?

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

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)

问题的根源在于 Bind 仅允许 vmPropertyviewProperty 参数中的属性 - 您不能通过函数调用更改它们。如果你不想改变你的视图模型,你可以使用 Bind 接受 IBindingTypeConverter which will simply negate your boolean value. Here is an example of 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 参数) .