Howa
Howa

Reputation: 60

Handle same events from different windows

I have a WPF project with two windows, the first window firing events and have it's own event handlers, the other window will fire the same events, any idea how to use handlers in first window to handle events in second window ?

Upvotes: 1

Views: 593

Answers (2)

Howa
Howa

Reputation: 60

thanks to @Cody Gray , @keyboardP and to this useful article http://geekswithblogs.net/lbugnion/archive/2007/03/02/107747.aspx

Here's a code snippet to demonstrate the answer:

first step add a new subclass :

using System.Windows;

namespace WpfApplication
{
   public class Subclass : Window
   {
    //Event handlers,functions or any potential reused code
   }
}

Second step: go to window1.xaml.cs

namespace WpfApplication
{
     public partial class Window1 : Subclass
     {
       public Window1()
       {
          InitializeComponent();
       }
     }
}

Third step: change the Xaml code for window1 as below:

<src:Subclass 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:WpfApplication"
    Title="Window1" Height="350" Width="525">
 </src:Subclass>

Finally do 2nd & 3rd steps for window2

Upvotes: 1

Natxo
Natxo

Reputation: 2947

A simple sample of what i was proposing in first place:

<Window x:Class="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>
        <Window Loaded="Window_Loaded"/>
        <Window Loaded="Window_Loaded"/>
    </Grid>
</Window>

Look how both windows share the event handler:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //Whatever
    }
}

At this point you should ask yourself if you really needed two windows, or any other container control could be enough.

Upvotes: 0

Related Questions