嗨,伙计们,我对Rx非常陌生,我想把一个简单的测试应用程序放在一起。它基本上使用Rx订阅窗口单击事件,并将文本框上的文本设置为“单击”。这是一个wpf应用程序。以下是xaml:
<Window x:Class="Reactive.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Canvas>
<TextBlock Name="txtClicked" Text="Rx Test"/>
</Canvas>
</Grid> 下面是代码:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
namespace Reactive
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
/// <summary>
/// Initializes a new instance of the <see cref="MainWindow"/> class.
/// </summary>
public MainWindow()
{
InitializeComponent();
var xs = from evt in Observable.FromEvent<MouseEventArgs>(this, "MouseDown")
select evt;
xs.ObserveOnDispatcher().Subscribe(value => txtClicked.Text = "Clicked");
}
}
}但出于某种原因,代码没有运行。我收到这样的信息:
对与指定绑定约束匹配的类型'Reactive.MainWindow‘上的构造函数的调用引发了异常。行号'3‘和线位置'9’
InnnerException消息:
事件委托必须是形式为void (object,T),其中T: EventArgs。
救命啊!
发布于 2011-01-17 03:30:39
可能为时已晚,但我建议您在需要从事件中观察到的时候使用强类型的FromEventPattern方法。
IObservable<IEvent<TEventArgs>> FromEventPattern<TDelegate, TEventArgs>(
Func<EventHandler<TEventArgs>, TDelegate> conversion,
Action<TDelegate> addHandler,
Action<TDelegate> removeHandler)
where TEventArgs: EventArgs在您的代码中,您可以这样使用它:
public partial class MainWindow : Window
{
/// <summary>
/// Initializes a new instance of the <see cref="MainWindow"/> class.
/// </summary>
public MainWindow()
{
InitializeComponent();
var xs = Observable
.FromEventPattern<MouseButtonEventHandler, MouseButtonEventArgs>(
h => (s, ea) => h(s, ea),
h => this.MouseDown += h,
h => this.MouseDown -= h);
_subscription = xs
.ObserveOnDispatcher()
.Subscribe(_ => txtClicked.Text = "Clicked");
}
private IDisposable _subscription = null;
}此外,您应该使用订阅变量(或订阅列表)来保存从IDisposable调用返回的Subscribe。就像在关闭表单时移除事件处理程序一样,您也应该在完成时处理订阅。
发布于 2010-07-23 05:24:16
我现在无法检查,但我相信问题是您使用了错误的EventArgs类。Window.MouseDown事件的类型为MouseButtonEventHandler,因此您应该使用MouseButtonEventArgs
var xs = Observable.FromEvent<MouseButtonEventArgs>(this, "MouseDown");(在这种情况下,查询表达式实际上没有做任何事情--如果要添加where子句等,可以将其放回。)
https://stackoverflow.com/questions/3315500
复制相似问题