我创建了一个类来监视属性的更改并触发INotifyPropertyChanged事件
但是,当将使用其的类添加到WPF控件时,设计器因未处理的异常而崩溃
System.Runtime.Remoting.RemotingException [4484]设计器进程意外终止!
有人知道为什么吗?
public interface IObservableValue<T>:INotifyPropertyChanged, INotifyPropertyChanging
{
T Value { get; }
}
public class ObservableProperty<T> : IObservableValue<T>
{
public static implicit operator T(ObservableProperty<T> obj)
{
return obj.Value;
}
public ObservableProperty()
:this(default(T))
{
}
public ObservableProperty(T value)
{
val = value;
CheckInterface(val, true);
}
T val;
public T Value
{
get { return val; }
set
{
if (!val.Equals(value))
{
OnPropertyChanging(changingArgs);
CheckInterface( val, false);
val = value;
CheckInterface( val, true);
OnPropertyChanged(changedArgs);
}
}
}
public bool HasValue
{
get { return val!=null; }
}
protected void CheckInterface<TValue>(TValue value, bool add)
{
INotifyPropertyChanging inc = value as INotifyPropertyChanging;
if (inc != null)
{
if (add)
inc.PropertyChanging += new PropertyChangingEventHandler(val_PropertyChanging);
else
inc.PropertyChanging -= new PropertyChangingEventHandler(val_PropertyChanging);
}
INotifyPropertyChanged inpc = value as INotifyPropertyChanged;
if (inpc != null)
{
if (add)
inpc.PropertyChanged += new PropertyChangedEventHandler(val_PropertyChanged);
else
inpc.PropertyChanged -= new PropertyChangedEventHandler(val_PropertyChanged);
}
INotifyCollectionChanged incc = value as INotifyCollectionChanged;
if (incc != null)
{
if (add)
incc.CollectionChanged += new NotifyCollectionChangedEventHandler(val_CollectionChanged);
else
incc.CollectionChanged -= new NotifyCollectionChangedEventHandler(val_CollectionChanged);
}
}
void val_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
OnPropertyChanged(changedArgs);
}
void val_PropertyChanging(object sender, PropertyChangingEventArgs e)
{
OnPropertyChanging(changingArgs);
}
void val_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnPropertyChanged(changedArgs);
}
void OnPropertyChanged(PropertyChangedEventArgs changed)
{
var handler = PropertyChanged;
if (handler != null) handler(this, changed);
}
void OnPropertyChanging(PropertyChangingEventArgs changed)
{
var handler = PropertyChanging;
if (handler != null) handler(this, changed);
}
private static PropertyChangedEventArgs changedArgs = new PropertyChangedEventArgs("Value");
private static PropertyChangingEventArgs changingArgs = new PropertyChangingEventArgs("Value");
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
}
我唯一看到的是这条线
if(!val.Equals(value))
NullReferenceException
为空时将抛出val
。另外,我敢打赌设计师会为该类使用默认的构造函数,这意味着val
在设计师中为null,因此值设置器会引发异常。
很奇怪,但是重新启动VS2012修复了它