簡體   English   中英

為什么` <Button Command={x:Static…}..>`有效但`</button> <Button Command={Binding…}..>`不有效?</button>

[英]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");
    }
}

我的代碼有什么問題? 我在弄東西嗎? 提前致謝。

因為

您可以對靜態字段或屬性進行x:Static引用

而field不是有效的綁定源 ,您需要將其轉換為property:

public ICommand StartCommand { get; set; }

並在例如costructructor中對其進行初始化

public ViewModel()
{
   StartCommand = new StartCommand();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM