我有以下课程...
class ExpressionBinder<T>
{
public Func<T> Getter;
public Action<T> Setter;
public T Value
{
get { return Getter.Invoke(); }
set { Setter.Invoke(value); }
}
public ExpressionBinder(Func<T> getter, Action<T> setter)
{
Getter = getter;
Setter = setter;
}
}
class ComparisonBinder<TSource, TValue> : ExpressionBinder<bool>, INotifyPropertyChanged
{
private TSource instance;
private TValue comparisonValue;
private PropertyInfo pInfo;
public event PropertyChangedEventHandler PropertyChanged;
public ComparisonBinder(TSource instance, Expression<Func<TSource, TValue>> property, TValue comparisonValue) : base(null,null)
{
pInfo = GetPropertyInfo(property);
this.instance = instance;
this.comparisonValue = comparisonValue;
Getter = GetValue;
Setter = SetValue;
}
private bool GetValue()
{
return comparisonValue.Equals(pInfo.GetValue(instance, null));
}
private void SetValue(bool value)
{
if (value)
{
pInfo.SetValue(instance, comparisonValue,null);
NotifyPropertyChanged("CustomerName");
}
}
private void NotifyPropertyChanged(string pName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(pName));
}
}
/// <summary>
/// Adapted from surfen's answer (https://stackoverflow.com/a/10003320/219838)
/// </summary>
private PropertyInfo GetPropertyInfo(Expression<Func<TSource, TValue>> propertyLambda)
{
Type type = typeof(TSource);
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expresion '{0}' refers to a property that is not from type {1}.",
propertyLambda,
type));
return propInfo;
}
}
我使用ComparisonBinder
该类的代码如下:
radioMale.DataBindings.Add(
"Checked",
new ComparisonBinder<DataClass, GenderEnum>(DataObj, (x) => x.Gender, GenderEnum.Male),
"Value",
false,
DataSourceUpdateMode.OnPropertyChanged);
radioFemale.DataBindings.Add(
"Checked",
new ComparisonBinder<DataClass, GenderEnum>(DataObj, (x) => x.Gender, GenderEnum.Male),
"Value",
false,
DataSourceUpdateMode.OnPropertyChanged);
它们允许我使用表达式将许多控件绑定到同一个属性,以生成控件绑定属性的值。它从控件到对象都很好地工作。(如果你想了解更多关于使用这个类和这个问题的信息)
现在,我需要另辟蹊径。当我更新我的对象(这将改变 get 表达式的结果)时,我需要更新绑定控件。我尝试实施,INotifyPropertyChanged
但没有任何区别。
一件奇怪的事情:将控件设置为DataSourceUpdateMode
以OnPropertyChanged
某种方式阻止我更改选中的收音机。