Sunday, 25 September 2011

WPF: Inheriting Window class



Problem: I am building a dash-board kind of application. Idea is we have a main window displaying various buttons which represent a ‘module’. On clicking these buttons we show a separate window. Now these ‘module’ windows can be closed, but if we invoke them again from the dash-board window we should re-use the Window object.

To solve the problem of showing the same Window object each time it is invoked we save the Window object in a list, and override the Close behavior.


Solution:
We create custom Window class and override the Closing method, so that Close is not called and we could reuse this object.


Implementation:

1> Create a custom class, let’s name it WindowBase.


Add the namespace “System.Windows”, inherit the class from Window:

    public class WindowBase : Window
    {
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            base.OnClosing(e);
        }
    }
Since we want to change the Closing behavior we override the OnClosing() method and set the e.Cancel = true. 

Now we will use WindowBase class to create all the “module” windows.
2> Create a new Window using WindowBase class. 
We add a new Window to the project, by right-clicking project and selecting Window. 
By default we will get the following XAML code in the newly added Window:

<Window x:Class="InheritWindow.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    <Grid>
        
    </Grid>
</Window>
Now since we are going to use a new class we need to define its namespace so that XAML can understand it.

So we:

> add:  xmlns:w="clr-namespace:InheritWindow"
> replace “Window” with “w:WindowBase”
> remove the inheritance from “Window1” class defined in in Window1.xaml.cs (We could change this to WindowBase but it is not necessary, as the inheritance hierarchy is set by XAML, where we are using <w:WindowBase>.)
And we are done! 

So the Window1 XAML looks like this:
<w:WindowBase x:Class="InheritWindow.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:w="clr-namespace:InheritWindow"
        Title="Window1" Height="300" Width="300">
    <Grid>

    </Grid>
</w:WindowBase>
And for completeness here is Window1.xaml.cs:
namespace InheritWindow
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1
    {
        public Window1()
        {
            InitializeComponent();
        }
    }
}



No comments:

Post a Comment

Note: only a member of this blog may post a comment.