[英]WPF - command binding not being called
I have a close button which is binding to a close command defined in my main viewmodel but for some reason it's not firing:我有一个关闭按钮,它绑定到我的主视图模型中定义的关闭命令,但由于某种原因它没有触发:
Button in mainview.xaml: mainview.xaml 中的按钮:
<Button Grid.Row="0" Style="{DynamicResource MyButtonStyle}" Margin="270,3,10,7"
Command="{Binding CloseCommand}"/>
Command declaration in MainViewModel: MainViewModel 中的命令声明:
public class MainViewModel : BaseViewModel
{
public ICommand CloseCommand { get; set; }
}
Command definition in CloseCommand.cs: CloseCommand.cs 中的命令定义:
public class CloseCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
System.Windows.Application.Current.Shutdown();
}
}
I set a breakpoint at CloseCommand but it isn't even getting there, what gives?我在 CloseCommand 处设置了一个断点,但它甚至没有到达那里,这是怎么回事?
I think that Sir Rufo is pointing out your problem.我认为 Rufo 爵士指出了您的问题。 But I'd like to recommend you to take a look at the Community Toolkit MVVM .
但我想推荐你看看社区工具包 MVVM 。 Its source generator will help you with your MVVM related code.
它的源代码生成器将帮助您处理 MVVM 相关代码。
For example, your ViewModel...例如,您的视图模型...
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace WpfCloseCommandSample;
[ObservableObject]
// This class needs to be "partial" for the source generator.
public partial class MainWindowViewModel
{
[ObservableProperty]
// The source generator will create a
// "ButtonName" property for you.
private string _buttonName;
[ICommand]
// The source generator will create a
// "CloseCommand" command for you.
private void Close()
{
System.Windows.Application.Current.Shutdown();
}
// Constructor
public MainWindowViewModel()
{
this.ButtonName = "Click here to close the window";
}
}
And your XAML...还有你的 XAML...
<Window
x:Class="WpfCloseCommandSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfCloseCommandSample"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid>
<Button Command="{Binding CloseCommand}" Content="{Binding ButtonName}" />
</Grid>
</Window>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.