最简单的方法是实现ButtonClick
事件处理程序并调用Window.Close()
方法,但是如何通过Command
绑定实现这一点呢?
发布于 2009-07-01 14:18:32
我认为在现实世界中,一个简单的点击处理程序可能比过于复杂的基于命令的系统更好,但你可以这样做:
使用本文http://msdn.microsoft.com/en-us/magazine/dd419663.aspx中的RelayCommand
public class MyCommands
{
public static readonly ICommand CloseCommand =
new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
Command="{X:Static local:MyCommands.CloseCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}}"/>
发布于 2009-06-30 21:02:50
所需要的只是一点XAML...
<Window x:Class="WCSamples.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close"
Executed="CloseCommandHandler"/>
</Window.CommandBindings>
<StackPanel Name="MainStackPanel">
<Button Command="ApplicationCommands.Close"
Content="Close Window" />
</StackPanel>
</Window>
还有一点C#..。
private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
this.Close();
}
(改编自this MSDN article)
发布于 2015-04-16 00:53:40
对于.NET 4.5 SystemCommands类可以做到这一点( WPF Shell扩展.NET 4.0用户可以使用google - Microsoft.Windows.Shell或Nicholas解决方案)。
<Window.CommandBindings>
<CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}"
CanExecute="CloseWindow_CanExec"
Executed="CloseWindow_Exec" />
</Window.CommandBindings>
<!-- Binding Close Command to the button control -->
<Button ToolTip="Close Window" Content="Close" Command="{x:Static SystemCommands.CloseWindowCommand}"/>
在代码背后,您可以像这样实现处理程序:
private void CloseWindow_CanExec(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void CloseWindow_Exec(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
https://stackoverflow.com/questions/1065887
复制相似问题