【问题标题】:Desperately need help on Rx.Net在 Rx.Net 上迫切需要帮助
【发布时间】:2010-07-23 05:03:59
【问题描述】:

大家好,我对 Rx 非常非常非常陌生,正在尝试组合一个简单的测试应用程序。它基本上使用 Rx 订阅窗口单击事件,并将文本框上的文本设置为“已单击”。这是一个 wpf 应用程序。这是xml:

<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 Handler(object, T) where T : EventArgs。

请帮忙!!!

【问题讨论】:

标签: c# wpf system.reactive


【解决方案1】:

可能为时已晚,但我建议您在想要从事件中观察到可观察对象时使用强类型 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;
}

您还应该使用订阅变量(或订阅列表)来保存从Subscribe 调用返回的IDisposable。就像在您关闭表单时删除事件处理程序一样,您也应该在完成后处理您的订阅。

【讨论】:

    【解决方案2】:

    我现在无法检查,但我认为问题在于您使用了错误的 EventArgs 类。 Window.MouseDown 事件的类型是 MouseButtonEventHandler,所以你应该使用 MouseButtonEventArgs

    var xs = Observable.FromEvent<MouseButtonEventArgs>(this, "MouseDown");
    

    (在这种情况下,您的查询表达式实际上并没有做任何事情 - 如果您想添加 where 子句等,可以将其放回原处。)

    【讨论】:

      猜你喜欢
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 2011-06-23
      • 2014-11-04
      • 1970-01-01
      • 2022-08-21
      • 1970-01-01
      相关资源
      最近更新 更多