Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing event in Custom Usercontrol - Window Store App

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?

like image 460
JayDev Avatar asked Nov 01 '22 20:11

JayDev


2 Answers

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;
    }
}
like image 57
Nono Avatar answered Nov 08 '22 14:11

Nono


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.

like image 32
helloserve Avatar answered Nov 08 '22 13:11

helloserve