gpt4 book ai didi

c# - 在 WPF 中关闭没有代码隐藏的窗口

转载 作者:太空狗 更新时间:2023-10-30 01:04:34 25 4
gpt4 key购买 nike

是否可以绑定(bind)一个 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 :

When you set the IsCancel property of a Button to true, you create a Button that is registered with the AccessKeyManager. The button is then activated when a user presses the ESC key.

现在,如果您单击此按钮,或按 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" ... />

关于c# - 在 WPF 中关闭没有代码隐藏的窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22829704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com