【问题标题】:Invoke Command Within Custom User Control在自定义用户控件中调用命令
【发布时间】:2011-06-25 18:14:48
【问题描述】:

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

这是我创建的简单用户控件:

<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(后面没有代码)

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

有人知道为什么吗??? 非常感谢。

【问题讨论】:

  • UserControl 的数据上下文如何设置?需要将其设置为 ViewModel 才能正确绑定。
  • 我已经在包裹userControl按钮的stackPanel标签里面添加了DataContext="MyUserControlViewModel",还是不行

标签: wpf mvvm


【解决方案1】:

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

例如,

this.DataContext = new MyViewModel();

在您的 XAML 中,删除

DataContext="MyUserControlViewModel"

因为 DataContext 将从主窗口继承。

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

【讨论】:

  • 好的,效果很好,但是如果主窗口包含多个控件怎么办,我每次都需要根据焦点控件的ViewModel设置窗口的DataContext吗??
  • 如果您的主窗口有多个用户控件,您可以在主窗口的构造函数中设置每个用户控件的DataContext。例如 this.userControl1.DataContext = MyViewModel1;
猜你喜欢
  • 1970-01-01
  • 2011-12-16
  • 2016-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
相关资源
最近更新 更多