WPF按钮单击和命令不能一起工作MVVM

Sto*_*dza 4 c# wpf mvvm

我正在使用mvvm开发一些wpf应用程序.我正在尝试使用按钮单击事件和命令,但命令永远不会执行.此外,当我只使用没有点击事件的命令时,它完美无缺.这是代码:

<ControlTemplate x:Key="reminderDataTemplate">          
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="25" />
            <RowDefinition Height="150" />
            <RowDefinition Height="20" />
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Content="New reminder:" HorizontalAlignment="Left" />
        <TextBox Text="{Binding Path=ReminderText, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Height="150" Width="200" HorizontalAlignment="Left"/>
        <Button Name="btnSaveReminder" Grid.Row="2" Content="Save" Width="auto" Height="20" HorizontalAlignment="Left" Click="btnSaveReminder_Click"  Command="{Binding Path= btnSaveReminder}"  />
    </Grid>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

只是提到我必须一起使用click和command因为我的视图和viewmodel在不同的项目中.

更新: 另外要说的是,当我在控制模板外的按钮中一起使用click和command时,一切都很完美.

eba*_*lga 16

Click event执行命令.

private void btnClick(object sender, RoutedEventArgs e)
{
    var btn = sender as Button;
    btn.Command.Execute(btn.CommandParameter);
}
Run Code Online (Sandbox Code Playgroud)

  • 最好在调用`Execute()`之前检查`CanExecute()`.请注意,如果您的命令可能不可用,则应根据命令状态验证是否仍在启用/禁用该按钮.如果命令未按预期组合"单击"执行,则按钮状态也可能无法正确更新. (8认同)