How to wire up a click event for a custom usercontrol button? Should I use CustomControl?
custom-controls, mouseevent, user-controls, wpf
Solution
The easiest option would be to just make your UserControl expose a click event, and pass through your Button's click event.
In MyButton's xaml:
<Button Width="Auto" HorizontalAlignment="Center" Click="onButtonClick">
In MyButton's code:
public event RoutedEventHandler Click;
void onButtonClick(object sender, RoutedEventArgs e)
{
if (this.Click != null)
{
this.Click(this, e);
}
}
You can then leave your "implementation" code as-is.
Problem
I wanted to create a button that had an image and a textblock as content. So I went about looking for an answer and found a post (Reusable Custom Content for Buttons) which told me to create a usercontrol. I did this and it works great. I can set the image source and text through dependency properties. However, I am stuck as there is no click event for my control. I did a little more digging and concluded that I probably need a CustomControl derived from Button. Is this correct? Or would it be better to wire up a click event to my UserControl? Here's my UserControl: ``` <UserControl x:Class="Client.Usercontrols.MyButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinHeight="30" MinWidth="40" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <Button Width="Auto" HorizontalAlignment="Center"> <Border CornerRadius="5" BorderThickness="1" BorderBrush="Transparent" > <Grid> <Image Name="tehImage" Source="{Binding ImageSource}" /> <TextBlock Name="tehText" Text="{Binding Text}" Style="{DynamicResource ButtonText}" /> </Grid> </Border> </Button> </UserControl> ``` Implementation ``` <my:MyButton ImageSource="../Images/MainSyncButton.png" ImageWidth="141" Text="Synchronise" Click="btnSynchronise_Click" /> ```