WPF 按钮单击和命令不能一起使用 MVVM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20565719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:12:04  来源:igfitidea点击:

WPF button click and command doesn't work together MVVM

c#wpfmvvm

提问by Stojdza

I'm developing some wpf application, using mvvm. I'm trying to use button click event and command together but command never get executed. Also when I use only command without click event it works perfect. Here is the code:

我正在使用 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>

Why is this happening?

为什么会这样?

Just to mention that I must use click and command together becouse my view and viewmodel are in different projects.

只是提到我必须同时使用 click 和 command 因为我的视图和视图模型在不同的项目中。

UPDATE:Also to say that, when I use click and command together in buttons outside of control template, everything works perfect.

更新:还要说的是,当我在控件模板之外的按钮中一起使用单击和命令时,一切正常。

回答by ebattulga

on the Click event, execute command.

Click event,执行命令。

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