WPF Common Window Behaviour
I am trying to define common behaviours between windows in a WPF application, for example: All dialogs need to have certain properties set a certain way and respond to the escape key in order to close.
Is there any way to inherit from a shared base class? The xa开发者_如何学编程ml kicks up a fuss every time I attemp this by including the namespace in the xaml.
Thank you.
Sounds like what you really want is a common style for your Windows, see here for a discussion around the topic: How to set default WPF Window Style in app.xaml?
If you still want to use a base window class, below works for me:
XAML:
<WpfApplication1:BaseWindow x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfApplication1="clr-namespace:WpfApplication1">
<StackPanel>
<Button Content="Click me" />
</StackPanel>
</WpfApplication1:BaseWindow>
Code behind:
using System.Windows;
using System.Windows.Media;
namespace WpfApplication1
{
public class BaseWindow : Window
{
public BaseWindow()
{
Background = Brushes.Red;
KeyDown += (sender, e) => { if (e.Key == Key.Escape) Close(); };
}
}
public partial class Window1
{
public Window1()
{
InitializeComponent();
}
}
}
The base class-method is described here: http://geekswithblogs.net/lbugnion/archive/2007/03/02/107747.aspx, I tried it and it worked for me. You may define the base class that way or similar:
public class BaseWindow : Window
{
public BaseWindow()
{
this.KeyDown += (sender, e) =>
{
//Checking wether escape is pressed...
};
}
}
Then you can easily use that now:
<local:BaseWindow x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Test"
Title="MainWindow" Height="350" Width="525">
<Grid>
</Grid></local:BaseWindow>
Of course you have to change the baseclass in the codebehind too.
精彩评论