2010-02-24 98 views
6

我敢打賭,這已經回答過很多次處理一個ApplicationCommand,但是...WPF - 在視圖模型

對於一個簡單的情況下在用戶控件按鈕具有它的命令屬性設置爲類似查找(ApplicationCommands .Find)ViewModel如何處理該命令?我平時看到的命令處理程序有線了與被添加到一個集合化CommandBindings上的UIElement一個的CommandBinding,但我的視圖模型不自UIElement派生(應該吧?)。命令本身不會在執行時通知事件通知,因此我應該在哪裏連接以獲取該信息?

編輯:我想用股票WPF如果可能的話要解決的問題。我知道這種事情有很多可用的框架,但希望簡化代碼。

EDIT2:包含一些示例代碼。

<UserControl> 
    <UserControl.DataContext> 
    <local:MyViewModel/> 
    </UserControl.DataContext> 

    <Button Command="Find"/> 
</UserControl> 

其中:

class MyViewModel 
{ 
    // Handle commands from the view here. 
} 

我可以一的CommandBinding添加到將處理執行的用戶控件,然後調用在MyViewModel一個假設的查找方法來完成實際的工作,但這是額外和不必要的代碼。我寧願如果ViewModel本身處理查找命令。一種可能的解決方案是讓MyViewModel從UIElement派生,然而這看起來不直觀。

回答

4

命令的目的是去耦,其生成從執行它的代碼的順序的代碼。因此:如果你想緊耦合的,你應該做的更好,通過事件:

<UserControl ... x:Class="myclass"> 
    ... 
    <Button Click="myclass_find" .../> 
    ... 
</UserControl> 

鬆耦合你需要添加一個CommandBindingUserControl

<UserControl ... > 
    <UserControl.DataContext> 
     <local:MyViewModel/> 
    </UserControl.DataContext> 

    <UserControl.CommandBindings> 
     <Binding Path="myFindCommandBindingInMyViewModel"/> 
    </UserControl.CommandBindings> 
    ... 
    <Button Command="ApplicationComamnd.Find" .../> 
    ... 
</UserControl> 

(不知道語法)

或者您可以在構造函數中爲您的UserControlCommandBindings添加一個CommandBinding,將val從ViewNodel UE:

partial class MyUserControl : UserControl 
{ 
    public MyUSerControl() 
    { 
     InitializeComponent(); 
     CommandBinding findCommandBinding = 
        ((MyViewModel)this.DataContext).myFindCommandBindingInMyViewModel; 
     this.CommandBindings.Add(findCommandBinding); 
    } 
} 
+0

我寧願鬆耦合的,所以我正在尋找演示瞭如何在一個類從用戶控件單獨處理命令的答案。 – 2010-02-24 18:43:17

+0

是否要爲所有來源以相同的方式處理ApplicationCommands.Find? – Vlad 2010-02-24 19:11:31

+0

添加了一些代碼來闡明我想要處理命令執行的位置 - 我想處理ViewModel中的命令,而不是在UserControl本身中處理一般的MVVM原理。 – 2010-02-24 19:44:09