I seem to be having a problem exposing events in Xaml. I have declared a public eventhandler in a custom user control like such.
public sealed partial class FoodItemControl : UserControl
{
public event EventHandler<StringEventArgs> thumbnailClicked;
public FoodItemControl()
{
InitializeComponent();
(this.Content as FrameworkElement).DataContext = this;
}
private void Thumbnail_Tapped(object sender, TappedRoutedEventArgs e)
{
var handler = thumbnailClicked;
if (handler != null)
{
handler(this, new StringEventArgs());
}
}
}
But when I go to assign an event to it in xaml the exposed eventhandler can't be found. I.e
<local:FoodItemControl thumbnailClicked="SOMETHING" />
Am I missing something in the example I found?
EDIT: It would seem that my problem was that I was defining the event as a EventHandler< StringEventArgs >. It worked once I changed this to simply EventHandler I.e
public event EventHandler thumbnailedClicked;
However I still do not really understand why?
You have to create a dependency property and register the property to expose it in a user control :
public sealed partial class FoodItemControl : UserControl
{
public EventHandler thumbnailClicked
{
get { return (EventHandler)GetValue(thumbnailClickedProperty); }
set { SetValue(thumbnailClickedProperty, value); }
}
public static readonly DependencyProperty thumbnailClickedProperty =
DependencyProperty.Register("thumbnailClicked", typeof(EventHandler),
typeof(FoodItemControl), new PropertyMetadata(""));
public FoodItemControl()
{
this.InitializeComponent();
(this.Content as FrameworkElement).DataContext = this;
}
}
You can also use the TypedEventHandler
type:
public event TypedEventHandler<FoodItemControl, StringEventArgs> thumbnailClicked;
This allows you to specify your own event arguments class that derive from EventArgs
.
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