Binuriki Cliean Jay
Binuriki Cliean Jay

Reputation: 98

How to have events in WPF user control

I got a user control:

<UserControl x:Class="NeocClinic.WPFSystem.Templatas.FunctionButtonsUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" >
    <Grid Name="GridFunctionButtons" Margin="5" >
        <Grid.ColumnDefinitions >
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <Button Name="btnExecute" Content="Execute" MinHeight="50" MinWidth="120" Grid.Column="0"/>
        <Button Name="btnUndo" Content="Undo" MinHeight="50" MinWidth="120" Grid.Column="1"/>
        <Button Name="btnBack" Content="Back" MinHeight="50" MinWidth="120" Grid.Column="2"/>
        <Button Name="btnDelete" Content="Delete" MinHeight="50" MinWidth="120" Grid.Column="3"/>

    </Grid>
</UserControl>

I used it in my Windows form XAML:

<windowsControls:FunctionButtonsUserControl x:Name="UserControlFunctionButtons" Grid.Row="5" Grid.Column="0" />

I can now see the buttons in my C# code, but the problem is the events. The four buttons must have each events but differs with each form that I deployed it, so I can't put the events in the usercontrol.xaml.

Upvotes: 1

Views: 116

Answers (2)

Ivan I
Ivan I

Reputation: 9990

You need to have the same events in the UserControl and then you subscribe to them on the "form" (though it is not proper WPF terminology), and then you can raise new events from there if that is required or call appropriate methods...

EDIT: To raise events from UserControl, just declare them in code behind like (updated later according the comments below):

public event RoutedEventHandler MyEvent;
private void button_Clicked(object sender, RoutedEventArgs e)
{
    if (MyEvent != null)
        MyEvent(this, e);
}

This is from the head without editor, so I might wrote something wrong, but you'll get the idea.

Upvotes: 1

BradleyDotNET
BradleyDotNET

Reputation: 61339

There are two ways to approach this problem:

  1. Use Routed Events. This lets you put events on your UserControl that the "owning" XAML can use and register for. The internal buttons would then raise these events. For more information on Routed Events, see MSDN.

  2. Use Commands exposed as DepenencyProperty. This allows the "owning" XAML to bind commands to your user control, which would then be invoked by your buttons. You could even bind the exposed Command properties straight to the button's.

The second is prefered since it stays within MVVM, but both will work.

Upvotes: 0

Related Questions