WPF 按钮单击和命令不能一起使用 MVVM [英] WPF button click and command doesn't work together MVVM
本文介绍了WPF 按钮单击和命令不能一起使用 MVVM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 mvvm 开发一些 wpf 应用程序.我正在尝试同时使用按钮单击事件和命令,但命令永远不会被执行.此外,当我只使用没有点击事件的命令时,它工作得很好.代码如下:
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:
<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>
为什么会这样?
顺便提一下,我必须同时使用 click 和 command,因为我的视图和视图模型在不同的项目中.
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.
推荐答案
在 Click 事件
上,执行命令.
private void btnClick(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
btn.Command.Execute(btn.CommandParameter);
}
这篇关于WPF 按钮单击和命令不能一起使用 MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文