I've created a custom user control. Is it possible for me to add a click event so that when someone clicks anywhere in the area of the control, a click event is fired?
The user control is defined as:
XAML:
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<StackPanel Orientation="Vertical">
<Image Source="{Binding TabItemImage}" HorizontalAlignment="Center" Stretch="None" VerticalAlignment="Top" />
<TextBlock Text="{Binding TabItemText}" FontSize="15" HorizontalAlignment="Center" VerticalAlignment="Bottom" />
</StackPanel>
</Grid>
C#:
public partial class TabItem : UserControl
{
public static readonly DependencyProperty ImageProperty = DependencyProperty.Register("TabItemImage", typeof(string), typeof(TabItem), null);
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("TabItemText", typeof(string), typeof(TabItem), null);
public string TabItemImage
{
get { return (string)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
public string TabItemText
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public TabItem()
{
InitializeComponent();
this.DataContext = this;
}
}
With the usage simply:
<tabs:TabItem TabItemText="OVERVIEW" TabItemImage="/Resources/Images/overview.png" />
Ideally I'd be able to modify the user control so that I could specify the click event, e.g.
<tabs:TabItem
TabItemText="OVERVIEW"
TabItemImage="/Resources/Images/options_64.png"
Click="TabItem_Clicked"/> <!-- when someone clicks the control, this fires -->
Is this possible? If so, what do I need to do to create a click event on a custom user control?
You need to add custom
RoutedEvent
to your TabItem UserControl, Below is code to add a Custom RoutedEvent:And then in your UserControl InitializeMethod wire up PreviewMouseLeftButtonUp event to fire your Custom RoutedEvent:
There is a pretty good How-to on MSDN discussing this, you might want to read that.
sthotakura, Has a good point and that would be a great way to do it. However, If you don't have more than one click event for this UserControl, Why dont you just use the any of the number of mouseclick events that come with defining a custom UserControl.
I didn't know you could set the datacontext to its self... That is interesting. I am going modify a custom Dialog that i created now.. :) Thanks for teaching me something.
XAML:
CS:
So, I can aswer at the great Post of Sthotakura.
this is your post with the all namespace needs
Add the following References: