如何通过单击“控制模板”中的按钮关闭窗口



我有一个名为winow1的窗口。这是我在window1.xaml 中写的代码

<Window x:Class="Template.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Style="{DynamicResource WindowStyle1}" Title="Window1">
<Grid></Grid>

App.xaml 中的代码

<Application.Resources>
    <Style x:Key="WindowStyle1" TargetType="{x:Type Window}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Window}">
                    <Grid>
                        <Button x:Name="button1" Click="button1_Click"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Application.Resources>

App.xaml.cs 中的代码

public partial class App : Application
{
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        //So what should I write here to close window1.
    }
}

谢谢你的建议。

我通常在App.cs 中使用此函数

private void btnExit_Click(object sender, RoutedEventArgs e)
{
    var b = e.OriginalSource as System.Windows.Controls.Button;
    var w = b.TemplatedParent as Window;
    w.Close();
}

Window类上使用静态函数GetWindow

private void button1_Click(object sender, RoutedEventArgs e)
{
    var window = Window.GetWindow(sender as DependencyObject);
    if (window != null) window.Close();
}

如果您想从应用于控件(而不是窗口本身)的模板中关闭窗口,请使用以下代码:

private void OnButtonClick(object sender, RoutedEventArgs e)
{
    Button button = (Button)sender;
    Window window = Window.GetWindow(button);
    window .Close();
}

这是获取Window的常用方法。

最新更新