[英]Why does `<Button Command={x:Static…}..>` works but `<Button Command={Binding…}..>` doesn't?
我是WPF的新手,我正在嘗試實現自定義Command
,我所做的是實現了ICommand
接口,並使用兩種方式將該實現綁定到按鈕上:一種是使用靜態擴展Marckup,另一種是使用普通擴展綁定,它可以與{x:Static}
,但在使用{Binding}
時失敗,並顯示此錯誤
System.Windows.Data錯誤:39:BindingExpression路徑錯誤:在“對象”“ ViewModel”(HashCode = 30880833)上找不到“ StartCommand”屬性。 BindingExpression:Path = StartCommand; DataItem ='ViewModel'(HashCode = 30880833); 目標元素是'Button'(Name =''); 目標
這是我的代碼
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");
}
}
我的代碼有什么問題? 我在弄東西嗎? 提前致謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.