iLe*_*ing 62 wpf button wpf-controls commandbinding
最简单的方法是实现ButtonClick事件处理程序和调用Window.Close()方法,但是如何通过Command绑定来实现呢?
Nic*_*ong 71
只需要一点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>
Run Code Online (Sandbox Code Playgroud)
还有一点C#......
private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
this.Close();
}
Run Code Online (Sandbox Code Playgroud)
(改编自此MSDN文章)
the*_*Dmi 62
实际上,没有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>
Run Code Online (Sandbox Code Playgroud)
为了使其工作,只需将x:Name窗口设置为"窗口",然后添加以下两个命名空间:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
Run Code Online (Sandbox Code Playgroud)
这要求您将Expression Blend SDK DLL添加到项目中,具体而言Microsoft.Expression.Interactions.
如果您没有Blend,可以在此处下载SDK .
Nir*_*Nir 49
我认为在现实世界的场景中,简单的点击处理程序可能比过于复杂的基于命令的系统更好,但你可以这样做:
使用本文中的RelayCommand http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
public class MyCommands
{
public static readonly ICommand CloseCommand =
new RelayCommand( o => ((Window)o).Close() );
}
Run Code Online (Sandbox Code Playgroud)
<Button Content="Close Window"
Command="{X:Static local:MyCommands.CloseCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}}"/>
Run Code Online (Sandbox Code Playgroud)
pog*_*ama 42
我所知道的最简单的解决方案是将IsCancel属性设置为关闭的true Button:
<Button Content="Close" IsCancel="True" />
Run Code Online (Sandbox Code Playgroud)
不需要绑定,WPF会自动为您完成!
对于.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}"/>
Run Code Online (Sandbox Code Playgroud)
在代码隐藏中,您可以像这样实现处理程序:
private void CloseWindow_CanExec(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void CloseWindow_Exec(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
Run Code Online (Sandbox Code Playgroud)