Reputation: 1
I have a window named winow1. Here is the code I wrote in 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>
Code in 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>
Code in 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.
}
}
Thanks for advice.
Upvotes: 0
Views: 240
Reputation: 2781
If you want to close a Window from a template which is applied to a control (not the Window itself) use this code:
private void OnButtonClick(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
Window window = Window.GetWindow(button);
window .Close();
}
This is common way to get a Window.
Upvotes: 0
Reputation: 4568
Use the static function GetWindow
on the Window
class:
private void button1_Click(object sender, RoutedEventArgs e)
{
var window = Window.GetWindow(sender as DependencyObject);
if (window != null) window.Close();
}
Upvotes: 0
Reputation: 879
i usually use this Function in 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();
}
Upvotes: 1