[英]Why does `<Button Command={x:Static…}..>` works but `<Button Command={Binding…}..>` doesn't?
I'm new to WPF, and I'm trying to implement a custom Command
, what I did is that I implemented the ICommand
interface and I bound that implementation to a button using two ways one with a Static Extention Marckup and one with a normal Binding, it works fine with {x:Static}
, but fails with this error when using {Binding}
我是WPF的新手,我正在尝试实现自定义
Command
,我所做的是实现了ICommand
接口,并使用两种方式将该实现绑定到按钮上:一种是使用静态扩展Marckup,另一种是使用普通扩展绑定,它可以与{x:Static}
,但在使用{Binding}
时失败,并显示此错误
System.Windows.Data Error: 39 : BindingExpression path error: 'StartCommand' property not found on 'object' ''ViewModel' (HashCode=30880833)'.
System.Windows.Data错误:39:BindingExpression路径错误:在“对象”“ ViewModel”(HashCode = 30880833)上找不到“ StartCommand”属性。 BindingExpression:Path=StartCommand;
BindingExpression:Path = StartCommand; DataItem='ViewModel' (HashCode=30880833);
DataItem ='ViewModel'(HashCode = 30880833); target element is 'Button' (Name='');
目标元素是'Button'(Name =''); target
目标
here is my code 这是我的代码
XAML 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>
Code behind 后面的代码
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");
}
}
What's wrong with my code? 我的代码有什么问题? am I messing something?
我在弄东西吗? thanks in advance.
提前致谢。
Because 因为
You can make
x:Static
references to static fields or properties您可以对静态字段或属性进行
x:Static
引用
whilst field is not a valid binding source and you need to convert it into property: 而field不是有效的绑定源 ,您需要将其转换为property:
public ICommand StartCommand { get; set; }
and initialize it for example in costructructor 并在例如costructructor中对其进行初始化
public ViewModel()
{
StartCommand = new StartCommand();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.