我有一个名为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.
}
}
感谢您的建议。
答案 0 :(得分:1)
我通常在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();
}
答案 1 :(得分:0)
使用GetWindow
类上的静态函数Window
:
private void button1_Click(object sender, RoutedEventArgs e)
{
var window = Window.GetWindow(sender as DependencyObject);
if (window != null) window.Close();
}
答案 2 :(得分:0)
如果要从应用于控件的模板(而不是Window本身)中关闭窗口,请使用以下代码:
private void OnButtonClick(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
Window window = Window.GetWindow(button);
window .Close();
}
这是获取窗口的常用方法。