Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么`<;按钮命令={x:Static…}..>;`有效,但`<;按钮命令={Binding…}..>;`不';T_C#_Wpf_Mvvm_Command - Fatal编程技术网

C# 为什么`<;按钮命令={x:Static…}..>;`有效,但`<;按钮命令={Binding…}..>;`不';T

C# 为什么`<;按钮命令={x:Static…}..>;`有效,但`<;按钮命令={Binding…}..>;`不';T,c#,wpf,mvvm,command,C#,Wpf,Mvvm,Command,我是WPF新手,正在尝试实现一个自定义的命令, 我所做的是实现了ICommand接口,并使用两种方式将该实现绑定到一个按钮,一种是静态扩展Marckup 还有一个是正常绑定的, 它可以在{x:Static}中正常工作,但在使用{Binding}时由于此错误而失败 System.Windows.Data错误:39:BindingExpression路径错误: 在“对象”“ViewModel”上找不到“StartCommand”属性 (HashCode=30880833)”。BindingExpre

我是WPF新手,正在尝试实现一个自定义的
命令
, 我所做的是实现了
ICommand
接口,并使用两种方式将该实现绑定到一个按钮,一种是静态扩展Marckup 还有一个是正常绑定的, 它可以在
{x:Static}
中正常工作,但在使用
{Binding}
时由于此错误而失败

System.Windows.Data错误:39:BindingExpression路径错误: 在“对象”“ViewModel”上找不到“StartCommand”属性 (HashCode=30880833)”。BindingExpression:Path=StartCommand; 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 ICommand StartCommand { get; set; }
并初始化它,例如在costructor中

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

谢谢,我完全忘记了我们不能使用字段作为绑定源
public ViewModel()
{
   StartCommand = new StartCommand();
}