2011-02-11 59 views
0

我新的WPF,我努力學習著名的MVVM模式, 我面對一個小問題(我相信)當我嘗試結合簡單的命令來一些視圖模型調用命令中的自定義用戶控件

這是簡單的用戶控件我已經創建了:

<UserControl x:Class="MVVM_UsingUserControl_Sample.View.MyUserControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300" 
      > 
     <StackPanel DataContext="MyUserControlViewModel" Orientation="Vertical" > 

     <Button Margin="0,100,0,0" Height="50" Width="50" Content="PressMe" Command="{Binding Path=MyCommand}"/> 

    </StackPanel> 

</UserControl> 

,這是用戶控制視圖模型

class MyUserControlViewModel : ViewModelBase 
{ 
     CommandBase m_MyCommand = null; 


     public MyUserControlViewModel() 
     { 

     } 

     public ICommand MyCommand 
     { 
      get 
      { 
       if (m_MyCommand == null) 
       { 
        m_MyCommand = new CommandBase(new Action<object>(DoSomething), 
                new Predicate<object>(CanDoSomething)); 
       } 

       return m_MyCommand; 
      } 
     } 

     public void DoSomething(object i_Params) 
     { 
      MessageBox.Show("Inside MyUserControl DoSomething"); 
     } 

     public bool CanDoSomething(object i_Params) 
     { 
      return true; 
     } 
} 

這是主窗口XAML(無碼behaind)

現在的問題是: 我的主窗口中包含的用戶控件的是,沒有別的(堆疊面板內)。 我期待命令「MyCommad」將得到調用,當我按下按鈕「myButton的」 但事實並非如此。

任何人有想法,爲什麼??? 非常感謝。

+0

UserControl的datacontext如何設置?它需要設置爲ViewModel才能正確綁定。 – 2011-02-11 19:09:59

+0

我添加的DataContext =「MyUserControlViewModel」封裝了用戶控件按鈕的StackPanel標籤裏面,不過它不工作 – Liran 2011-02-11 19:26:54

回答

2

在主窗口的構造函數,將其的DataContext你的視圖模型。

例如,

this.DataContext = new MyViewModel(); 

在XAML中,刪除

DataContext="MyUserControlViewModel" 

因爲在DataContext從主窗口繼承。然後

一切都應該按預期工作。