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" />
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With