【发布时间】: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",还是不行