C# 反应绑定:使用not(!)运算符绑定数据时出错
我正在尝试使用ReactiveUI版本6.5.0.0中的IReactiveBinding将视图模型中的字段绑定到控件的属性 我想将视图模型中的否定值绑定到控件的属性:C# 反应绑定:使用not(!)运算符绑定数据时出错,c#,system.reactive,reactiveui,C#,System.reactive,Reactiveui,我正在尝试使用ReactiveUI版本6.5.0.0中的IReactiveBinding将视图模型中的字段绑定到控件的属性 我想将视图模型中的否定值绑定到控件的属性: this.Bind(ViewModel, vm => !vm.IsSmth, control => _checkBoxSmth.Enabled, _checkBoxSmth.Events().CheckStateChanged) 但我只是得到这个错误,无法找到如何修复它 System.NotSupportedExce
this.Bind(ViewModel, vm => !vm.IsSmth, control => _checkBoxSmth.Enabled, _checkBoxSmth.Events().CheckStateChanged)
但我只是得到这个错误,无法找到如何修复它
System.NotSupportedException:不支持的表达式类型:'Not'在此处捕获:
有什么建议吗?我的建议是添加一个负字段并绑定到该字段。
下面是一个非常简单的概念示例
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
只允许vmProperty
和viewProperty
参数中的属性-不能通过函数调用更改它们。如果您不想更改视图模型,可以使用Bind
重载,它接受的值将简单地否定您的布尔值。下面是一个实现示例
您的代码可能如下所示(注意-我没有测试它):
请注意,如果使用
OneWayBind
,则不需要实现自己的转换器,存在接受函数更改视图模型属性的重载(查找selector
参数)。是的,这是我需要的。为了得到问题的完整答案,绑定应该这样做:this.Bind(ViewModel,vm=>vm.IsSmth,control=>control.\u checkBoxSmth.Enabled,null,new negationTypeConverter(),new negationTypeConverter())
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;
}
}