2010-07-23 83 views
0

嗨,大家好,我對Rx非常非常非常新,並試圖組合一個簡單的測試應用程序。它基本上使用Rx訂閱窗口單擊事件,並將文本框上的文本設置爲「單擊」。這是一個WPF應用程序。這裏的XAML:在Rx.Net上極度需要幫助

<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消息:

事件委託的形式必須是無效的處理程序(對象,T)其中,T:EventArgs的。

請幫忙!!!

+0

也許你可以從下面的例子中獲得幫助。 http://rxwiki.wikidot.com/101samples#toc6 – Ragunathan 2010-07-23 05:24:11

回答

2

我現在無法檢查,但我相信問題在於您使用了錯誤的EventArgs類。該Window.MouseDown事件是MouseButtonEventHandler型的,所以你應該使用MouseButtonEventArgs

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

(查詢表達式是不是真的做任何事情在這種情況下 - 你可以把它放回去,如果你想添加where子句等)

4

可能來不及了,但我建議您使用強類型的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; 
} 

而且你應該使用訂閱變量(或訂閱列表)來保存IDisposableSubscribe調用返回。就像在關閉表單時刪除事件處理程序一樣,當您完成時,您也應該處理訂閱。