Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to externally assign event handlers for controls inside an UserControl?

If I have a UserControl

<UserControl
    x:Class="UserInterface.AControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Button
            Content="Set"
            Name="setButton" />
    </Grid>
</UserControl>

How to externally assign an event handler for setButton when using this control?

<UserControl
    xmlns:my="clr-namespace:UserInterface"
    x:Class="UserInterface.AnotherControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <my:AControl />
    </Grid>
</UserControl>

Could I use something like?

        <my:AControl
              setButton.Click="setButton_Click" />
like image 768
Jader Dias Avatar asked Jan 24 '26 12:01

Jader Dias


1 Answers

You can't really do this, but what you can do is in your custom UserControl (AControl), expose a public event from it "SetButtonClicked", then subscribe to that. This assumes that SetButton exists on AControl.

For example, C# code for AControl would become

public class AControl : UserControl
{ 
    public event EventHandler<EventArgs> SetButtonClicked;

    public AControl ()
    {
        InitializeComponent();
        this.setButton.Click += (s,e) => OnSetButtonClicked;
    }
    protected virtual void OnSetButtonClicked()
    {
        var handler = SetButtonClicked;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
}

and in Xaml you would subscribe as follows

<my:AControl SetButtonClick="setbutton_Clicked"/>

Edit: I would ask what it is you are trying to achieve here though. if you wish to handle some additional behaviour outside of AControl then perhaps call the event something else? For instance do you want to just notify someone that a button was clicked, or that an operation completed? By encapsulating your custom behaviour for the click inside AControl you can expose the behaviour that consumers of AControl really care about. Best regards,

like image 133
Dr. Andrew Burnett-Thompson Avatar answered Jan 26 '26 03:01

Dr. Andrew Burnett-Thompson