问题
为什么在按钮和菜单项中禁用了WPF ApplicationCommands.Close命令?
代码
<Window x:Class="ApplicationCloseCommand.Views.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="clr-namespace:ApplicationCloseCommand.ViewModels"
mc:Ignorable="d"
Title="MainWindow" Height="169.493" Width="319.273">
<Window.DataContext>
<viewModels:MainWindowViewModel />
</Window.DataContext>
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="_Exit" Command="Close"/>
</MenuItem>
</Menu>
<Canvas>
<Button Content="Close" Command="Close" Height="23" VerticalAlignment="Top" Canvas.Left="142" Canvas.Top="31"/>
</Canvas>
</DockPanel>
</Window>
研究
Some sources说自己实现ICommand
并在命令处理程序中执行this.Close()
。但是然后,我根本不理解为什么ApplicationCommands.Close
存在。
Some sources说,需要实现一种CanExecute
方法来返回true
。但是同样,如果我必须自己做(包括链接的示例中的CloseCommandHandler
),那么ApplicationCommands.Close
有什么好处?
Some sources提到CommandTarget
。这不起作用:
<MenuItem Header="_Exit" Command="Close" CommandTarget="{Binding ElementName=MyMainWindow}"/>
我只是用CommandTarget
做错了吗?