最も簡単な方法は、イベント ハンドラーを実装してメソッドButtonClick
を呼び出すことですが、バインディングWindow.Close()
を介してこれを行うにはどうすればよいでしょうか。Command
7 に答える
必要なのは、少しの 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();
}
(この MSDN の記事から改作)
実際には、 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>
これを機能させるx:Name
には、ウィンドウの を「window」に設定し、次の 2 つの名前空間を追加します。
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
これには、Expression Blend SDK DLL をプロジェクトに追加する必要があります。具体的にはMicrosoft.Expression.Interactions
.
Blend がない場合は、SDK をここからダウンロードできます。
現実のシナリオでは、複雑すぎるコマンドベースのシステムよりも単純なクリック ハンドラーの方がおそらく優れていると思いますが、次のようなこともできます。
この記事の 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}}}"/>
ウィンドウが で表示された場合Window.ShowDialog()
:
私が知っている最も簡単な解決策IsCancel
は、 close のプロパティを true に設定することButton
です。
<Button Content="Close" IsCancel="True" />
バインディングは必要ありません。WPF が自動的に行います。
このプロパティは、これらがダイアログの「OK」および「キャンセル」ボタンであることを簡単に示す方法を提供します。また、ESCキーをボタンにバインドします。