我想获得一个控件的DataContext作为一个IObservable。我试过了:
Observable.FromEvent<DependencyPropertyChangedEventHandler,
DependencyPropertyChangedEventArgs>
(a => this.DataContextChanged += a, a => this.DataContextChanged -= a)
.Subscribe(e => MessageBox.Show(e.NewValue.ToString()));
可以很好地编译,但是在调用Subscribe时,它会抛出异常:错误绑定到目标方法。
我的猜测是,这是因为DependencyPropertyChangedEventArgs不从事件参数继承,但我不确定。如有任何正确的建议,我将不胜感激。
FromEvent的另一个重载之一允许您从方法中自己创建委托。允许你这样做:
Observable.FromEvent
<DependencyPropertyChangedEventHandler, DependencyPropertyChangedEventArgs>
(a => new DependencyPropertyChangedEventHandler(
new Action<object, DependencyPropertyChangedEventArgs>((s, e) => a(e))),
h => this.DataContextChanged += h, h => this.DataContextChanged -= h)
.Subscribe(e => MessageBox.Show(e.NewValue.ToString()));
似乎可以
您已经'击中了钉子',由于某种原因DependencyPropertyChangedEventArgs
是一个结构体,因此不继承EventArgs
。请看这个相关的博客文章:
这使得使用通用事件处理机制无法处理此事件。
我猜你将不得不在你自己的代码中处理这个事件,并手动创建一个Observable
。
自定义实现将非常简单,如:
Observable.CreateWithDisposable<DependencyPropertyChangedEventHandler>(obs =>
{
var subject = new Subject<DependencyPropertyChangedEventHandler>();
//Attach event handler and on event call OnNext of subject with the value
return subject.Subscribe(obs);
});
UPDATED:处理事件处理程序删除
public class GenericDisposable : IDisposable
{
Action _act = null;
IDisposable _disp = null;
public GenericDisposable(Action act,IDisposable disp)
{
_act = act;
_disp = disp;
}
public void Dispose()
{
_act();
_disp.Dispose();
}
}
public static IObservable<DependencyPropertyChangedEventHandler> CreateForEvent()
{
return Observable.Defer(() =>
{
return Observable.CreateWithDisposable<DependencyPropertyChangedEventHandler>(obs =>
{
var subject = new Subject<DependencyPropertyChangedEventHandler>();
//Attach event handler and on event call OnNext of subject with the value
return new GenericDisposable(() => {/*remove event handler*/}, subject.Subscribe(obs));
});
});
}