Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Dependency Properties for setting Custom EventHandlers in XAML

i want to do add custom event handlers to default framework elements using DependencyProperties.

Something like the following:

<Border custom:MyProps.HandleMyEvent="someHandler">...</Border>

Here is the code behind for the control that contains the Border element:

public class MyPage : Page{
    public void someHandler(object sender, EventArgs e){
        //do something
    }
}

Here is rough sample of how i imagine the class that defines the property:

public class MyProps{
    public event EventHandler MyInternalHandler;
    public static readonly DependencyProperty HandleMyEventProperty = ...
    public void SetHandleMyEvent(object sender, EventHandler e){
         MyInternalHandler += e;
    }
}

The problem is that I don't know/didn't find any hints how to combine DependencyProperties with events/delegates and EventHandlers.

Do you have a clue?

like image 926
Juve Avatar asked Feb 16 '10 10:02

Juve


1 Answers

I'm going to assume this has nothing to do with WPF, this is a silverlight question.

First of all you can't simply add an Event to an existing control. After all you are adding attached Properties whereas events are handled differently, they're not properties.

You need to create a new type which has this event then create an attached property of this type.

Here is a basic type that simply has an event:-

public class MyEventer
{
    public event EventHandler MyEvent;

    // What would call this??
    protected void OnMyEvent(EventArgs e)
    {
      if (MyEvent != null)
         MyEvent(this, e);
    }
}

Now we create an attached property which has MyEventer as its property, I prefer to place these in a separate static class.

public static class MyProps
{

  public static MyEventer GetEventer(DependencyObject obj)
  {
     return (MyEventer)obj.GetValue(EventerProperty );
  }

  public static void SetEventer(DependencyObject obj, MyEventer value)
  {
    obj.SetValue(EventerProperty , value);
  }

  public static readonly DependencyProperty EventerProperty =
        DepencencyProperty.RegisterAttached("Eventer", typeof(MyEventer), typeof(MyProps), null)

  }
}

Now you attach this to a control like this:-

<Border ...>
   <custom:MyProps.Eventer>
      <custom:MyEventer MyEvent="someHandler" />
   </custom:MyProps.Eventer>
</Border>

If you compile the project before writing this xaml you'll note that Visual Studio will offer you the option for it to create the event handler in the code behind for you.

Of course this still leaves a significant question: How did you intend to cause the event to fire?

like image 160
AnthonyWJones Avatar answered Nov 15 '22 10:11

AnthonyWJones