[英]Close Window without code-behind in WPF
是否可以將Button
綁定到關閉Window
而不添加代碼隱藏事件?
<Button Content="OK" Command="{Binding CloseWithSomeKindOfTrick}" />
而不是以下XAML:
<Button Content="OK" Margin="0,8,0,0" Click="Button_Click">
使用代碼隱藏:
private void Button_Click(object sender, RoutedEventArgs e)
{
Close();
}
謝謝!
如果要關閉對話框Window
,可以添加Button IsCancel
屬性:
<Button Name="CloseButton"
IsCancel="True" ... />
這意味着以下MSDN
:
將Button的
IsCancel
屬性設置為true時,將創建一個使用AccessKeyManager注冊的Button。 然后,當用戶按下ESC鍵時,該按鈕被激活 。
現在,如果單擊此按鈕,或按Esc,則對話框Window
正在關閉,但它不適用於正常的MainWindow
。
要關閉MainWindow
,只需添加一個已經顯示的Click處理程序。 但是,如果您想要一個滿足MVVM樣式的更優雅的解決方案,您可以添加附加的行為:
public static class ButtonBehavior
{
#region Private Section
private static Window MainWindow = Application.Current.MainWindow;
#endregion
#region IsCloseProperty
public static readonly DependencyProperty IsCloseProperty;
public static void SetIsClose(DependencyObject DepObject, bool value)
{
DepObject.SetValue(IsCloseProperty, value);
}
public static bool GetIsClose(DependencyObject DepObject)
{
return (bool)DepObject.GetValue(IsCloseProperty);
}
static ButtonBehavior()
{
IsCloseProperty = DependencyProperty.RegisterAttached("IsClose",
typeof(bool),
typeof(ButtonBehavior),
new UIPropertyMetadata(false, IsCloseTurn));
}
#endregion
private static void IsCloseTurn(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is bool && ((bool)e.NewValue) == true)
{
if (MainWindow != null)
MainWindow.PreviewKeyDown += new KeyEventHandler(MainWindow_PreviewKeyDown);
var button = sender as Button;
if (button != null)
button.Click += new RoutedEventHandler(button_Click);
}
}
private static void button_Click(object sender, RoutedEventArgs e)
{
MainWindow.Close();
}
private static void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
MainWindow.Close();
}
}
在MainWindow
使用此行為,如:
<Window x:Class="MyProjectNamespace.MainWindow"
xmlns:local="clr-namespace:MyProjectNamespace">
<Button Name="CloseButton"
local:ButtonBehavior.IsClose="True" ... />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.