在自定义用户控件中调用命令

时间:2011-02-11 18:44:18

标签: wpf mvvm

我是WPF的新手,我正在尝试学习着名的MVVM模式, 当我尝试将简单命令绑定到某个ViewModel时,我正面临一个小问题(我确定)

这是我创建的Simple UserControl:

<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>

这是User Control ViewModel

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(没有代码行为)                   

现在的问题是: 我的主窗口按原样包含userControl(在堆栈面板内),没有别的。 我希望当按下“MyButton”按钮时,命令“MyCommad”将被调用 但事实并非如此。

任何人都知道为什么??? 非常感谢。

1 个答案:

答案 0 :(得分:2)

在主窗口的构造函数中,将其DataContext设置为ViewModel。

例如,

this.DataContext = new MyViewModel();

在您的XAML中,删除

DataContext="MyUserControlViewModel"

因为DataContext将从主窗口继承。

然后一切都应该如你所愿。