2011-02-11 57 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从主窗口继承。然后

一切都应该按预期工作。