wpf 如何将关闭命令绑定到按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1065887/
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
How to bind Close command to a button
提问by iLemming
The easiest way is to implement ButtonClick
event handler and invoke Window.Close()
method, but how doing this through a Command
binding?
最简单的方法是实现ButtonClick
事件处理程序和调用Window.Close()
方法,但是如何通过Command
绑定来实现呢?
采纳答案by Nir
I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:
我认为在现实世界的场景中,一个简单的点击处理程序可能比过于复杂的基于命令的系统更好,但你可以这样做:
using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
使用本文中的 RelayCommand http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
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}}}"/>
回答by Nicholas Armstrong
All it takes is a bit of XAML...
只需要一点 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>
And a bit of C#...
还有一点C#...
private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
this.Close();
}
(adapted from this MSDN article)
(改编自这篇 MSDN 文章)
回答by theDmi
Actually, it ispossible without C# code.The key is to use interactions:
实际上,没有 C# 代码也是可能的。关键是使用交互:
<Button Content="Close">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
In order for this to work, just set the x:Name
of your window to "window", and add these two namespaces:
为了使其工作,只需将x:Name
窗口的设置为“window”,并添加这两个命名空间:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
This requires that you add the Expression Blend SDK DLL to your project, specifically Microsoft.Expression.Interactions
.
这要求您将 Expression Blend SDK DLL 添加到您的项目中,特别是Microsoft.Expression.Interactions
.
In case you don't have Blend, the SDK can be downloaded here.
如果您没有 Blend,可以在此处下载 SDK 。
回答by pogosama
The simplest solution that I know of is to set the IsCancel
property to true of the close Button
:
我所知道的最简单的解决方案是IsCancel
将 close的属性设置为 true Button
:
<Button Content="Close" IsCancel="True" />
No bindings needed, WPF will do that for you automatically!
无需绑定,WPF 会自动为您完成!
Reference: MSDN Button.IsCancel property.
回答by kiran
For .NET 4.5 SystemCommandsclass will do the trick (.NET 4.0 users can use WPF Shell Extension google - Microsoft.Windows.Shell or Nicholas Solution).
对于.NET 4.5 SystemCommands类将起作用(.NET 4.0 用户可以使用 WPF Shell Extension google - Microsoft.Windows.Shell 或 Nicholas Solution)。
<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}"/>
In the Code Behind you can implement the handlers like this:
在代码隐藏中,您可以像这样实现处理程序:
private void CloseWindow_CanExec(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void CloseWindow_Exec(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
回答by Andy Braham
In the beginning I was also having a bit of trouble figuring out how this works so I wanted to post a better explanation of what is actually going on.
一开始我在弄清楚它是如何工作的时候也遇到了一些麻烦,所以我想对实际发生的事情发表一个更好的解释。
According to my research the best way to handle things like this is using the Command Bindings. What happens is a "Message" is broadcast to everything in the program. So what you have to do is use the CommandBinding
. What this essentially does is say "When you hear this Message do this".
根据我的研究,处理此类事情的最佳方法是使用命令绑定。发生的事情是向程序中的所有内容广播“消息”。所以你要做的就是使用CommandBinding
. 这本质上是说“当你听到这个消息时,做这个”。
So in the Question the User is trying to Close the Window. The first thing we need to do is setup our Functions that will be called when the SystemCommand.CloseWindowCommand
is broadcast. Optionally you can assign a Function that determines if the Command should be executed. An example would be closing a Form and checking if the User has saved.
所以在问题中,用户试图关闭窗口。我们需要做的第一件事是设置将在SystemCommand.CloseWindowCommand
广播时调用的函数。您可以选择分配一个函数来确定是否应该执行命令。一个例子是关闭表单并检查用户是否已保存。
MainWindow.xaml.cs (Or other Code-Behind)
MainWindow.xaml.cs(或其他代码隐藏)
void CloseApp( object target, ExecutedRoutedEventArgs e ) {
/*** Code to check for State before Closing ***/
this.Close();
}
void CloseAppCanExecute( object sender, CanExecuteRoutedEventArgs e ) {
/*** Logic to Determine if it is safe to Close the Window ***/
e.CanExecute = true;
}
Now we need to setup the "Connection" between the SystemCommands.CloseWindowCommand
and the CloseApp
and CloseAppCanExecute
现在,我们需要设置之间的“连接”SystemCommands.CloseWindowCommand
和CloseApp
和CloseAppCanExecute
MainWindow.xaml (Or anything that implements CommandBindings)
MainWindow.xaml(或任何实现 CommandBindings 的东西)
<Window.CommandBindings>
<CommandBinding Command="SystemCommands.CloseWindowCommand"
Executed="CloseApp"
CanExecute="CloseAppCanExecute"/>
</Window.CommandBindings>
You can omit the CanExecute if you know that the Command should be able to always be executed Save might be a good example depending on the Application. Here is a Example:
如果您知道命令应该能够始终执行,则可以省略 CanExecute 保存可能是一个很好的示例,具体取决于应用程序。这是一个例子:
<Window.CommandBindings>
<CommandBinding Command="SystemCommands.CloseWindowCommand"
Executed="CloseApp"/>
</Window.CommandBindings>
Finally you need to tell the UIElement to send out the CloseWindowCommand.
最后,您需要告诉 UIElement 发出 CloseWindowCommand。
<Button Command="SystemCommands.CloseWindowCommand">
Its actually a very simple thing to do, just setup the link between the Command and the actual Function to Execute then tell the Control to send out the Command to the rest of your program saying "Ok everyone run your Functions for the Command CloseWindowCommand".
它实际上是一件非常简单的事情,只需设置命令和要执行的实际函数之间的链接,然后告诉控件将命令发送到程序的其余部分,说“好的,每个人都为命令 CloseWindowCommand 运行你的函数”。
This is actually a very nice way of handing this because, you can reuse the Executed Function all over without having a wrapper like you would with say WinForms (using a ClickEvent and calling a function within the Event Function) like:
这实际上是一种非常好的处理方式,因为您可以重用执行的函数,而无需像 WinForms 那样使用包装器(使用 ClickEvent 并在事件函数中调用函数),例如:
protected override void OnClick(EventArgs e){
/*** Function to Execute ***/
}
In WPF you attach the Function to a Command and tell the UIElement to execute the Function attached to the Command instead.
在 WPF 中,您将函数附加到命令,并告诉 UIElement 执行附加到命令的函数。
I hope this clears things up...
我希望这能解决问题...
回答by Joel Palmer
One option that I've found to work is to set this function up as a Behavior.
我发现可行的一种选择是将此功能设置为行为。
The Behavior:
行为:
public class WindowCloseBehavior : Behavior<Window>
{
public bool Close
{
get { return (bool) GetValue(CloseTriggerProperty); }
set { SetValue(CloseTriggerProperty, value); }
}
public static readonly DependencyProperty CloseTriggerProperty =
DependencyProperty.Register("Close", typeof(bool), typeof(WindowCloseBehavior),
new PropertyMetadata(false, OnCloseTriggerChanged));
private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = d as WindowCloseBehavior;
if (behavior != null)
{
behavior.OnCloseTriggerChanged();
}
}
private void OnCloseTriggerChanged()
{
// when closetrigger is true, close the window
if (this.Close)
{
this.AssociatedObject.Close();
}
}
}
On the XAML Window, you set up a reference to it and bind the Behavior's Close property to a Boolean "Close" property on your ViewModel:
在 XAML 窗口上,设置对它的引用并将 Behavior 的 Close 属性绑定到 ViewModel 上的布尔“Close”属性:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<i:Interaction.Behaviors>
<behavior:WindowCloseBehavior Close="{Binding Close}" />
</i:Interaction.Behaviors>
So, from the View assign an ICommand to change the Close property on the ViewModel which is bound to the Behavior's Close property. When the PropertyChanged event is fired the Behavior fires the OnCloseTriggerChanged event and closes the AssociatedObject... which is the Window.
因此,从 View 分配一个 ICommand 来更改绑定到 Behavior 的 Close 属性的 ViewModel 上的 Close 属性。当 PropertyChanged 事件被触发时,Behavior 会触发 OnCloseTriggerChanged 事件并关闭 AssociatedObject... 即窗口。