Handle all buttons click event in a single method in WPF

2011-01-12


Now we have a stack, we put multiple buttons into this stack, all these buttons will for similar popup windows when they are clicked, so want to handle all these buttons in a single method.

You might have multiple solution to write the single method, here we have a good sample:

xmal file:

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="" Height="400" Width="300">
    
    <StackPanel  Button.Click="theButton_Click">
        <TextBlock FontSize="12pt" FontWeight="Bold" 
               TextAlignment="Center" TextWrapping="Wrap">
            Single Method
        </TextBlock>

        <Button  FontSize="11pt">First Button</Button>
        <Button  FontSize="11pt">Second Button</Button>
        <Button  FontSize="11pt">Third Button</Button>
        <Button FontSize="11pt">Close</Button>

    </StackPanel>
</Window>

Code behind file:

private void theButton_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)e.Source;
            if (btn.Content.ToString() != "Close")
            {
                Type type = this.GetType();
                Assembly assembly = type.Assembly;
                Window window = (Window)assembly.CreateInstance(
                    type.Namespace + "." + btn.Content);
                window.ShowDialog();
            }
            else
                this.Close();
        }

then we have related popup WPF windows named "First Button", "Second Button", "Third Button":

For example:

First Button.xaml:

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="First Button Window" Height="300" Width="300">
    <Grid>
        <StackPanel>
            <TextBlock Name="textBlock" Height="30" TextAlignment="Center" Text="Hello! This is Button 1 popup Window" />
            <Button  Content="OK" />
        </StackPanel>
    </Grid>
</Window>