【发布时间】:2014-02-21 23:53:34
【问题描述】:
我是 WPF 新手,我正在尝试实现自定义 Command,
我所做的是我实现了ICommand 接口,并使用两种方式将该实现绑定到一个按钮,一种是静态扩展标记
和一个具有正常绑定的,
它适用于{x:Static},但在使用{Binding} 时失败并出现此错误
System.Windows.Data 错误:39:BindingExpression 路径错误: 在“对象”“ViewModel”上找不到“StartCommand”属性 (哈希码=30880833)'。绑定表达式:路径=开始命令; DataItem='ViewModel' (HashCode=30880833);目标元素是“按钮” (名称='');目标
这是我的代码
XAML
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="75" Width="300">
<StackPanel Orientation="Horizontal" Height="30">
<Button Command="{Binding StartCommand}" Content="Start" Margin="5,0"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</Window>
背后的代码
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new ViewModel { Name = "Simple property" };
}
}
class ViewModel
{
public string Name { get; set; }
// static to use with {x:Static}
public ICommand StartCommand = new StartCommand();
}
class StartCommand : ICommand
{
public bool CanExecute(object parameter)
{
return false;
}
public event System.EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
MessageBox.Show("Start Executed");
}
}
我的代码有什么问题?我在搞砸什么吗? 提前致谢。
【问题讨论】: