【问题标题】:Why does `<Button Command={x:Static...}..>` works but `<Button Command={Binding...}..>` doesn't?为什么 `<Button Command={x:Static...}..>` 有效但 `<Button Command={Binding...}..>` 无效?
【发布时间】: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");
    }
}

我的代码有什么问题?我在搞砸什么吗? 提前致谢。

【问题讨论】:

    标签: c# wpf mvvm command


    【解决方案1】:

    因为

    您可以使x:Static 引用静态字段或属性

    虽然字段不是有效的binding source,但您需要将其转换为属性:

    public ICommand StartCommand { get; set; }
    

    例如在构造函数中初始化它

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

    【讨论】:

    • 谢谢,我完全忘记了我们不能使用字段作为绑定源
    猜你喜欢
    • 1970-01-01
    • 2014-06-22
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多