John Edwards
John Edwards

Reputation: 1546

Routed events and Dependency propetries

I have a user control with a dependency property. When that property is changed, I want to cascade a RoutedEvent up to the main application and execute some function. Here is my user control code:

    public TCardBase SelectedTCard
    {
        get { return (TCardBase)GetValue(SelectedTCardProperty); }
        set { SetValue(SelectedTCardProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SelectedTCard.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SelectedTCardProperty =
        DependencyProperty.Register("SelectedTCard", typeof(TCardBase), typeof(TCardView), new PropertyMetadata(SelectedTCardPropertyChanged));


    private static void SelectedTCardPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
       //SEND EVENT HERE TO MAIN APPLICATION
    } 

What is the best way to send this event to the main application? Thanks.

Upvotes: 0

Views: 627

Answers (1)

dev hedgehog
dev hedgehog

Reputation: 8791

There are plenty of nice examples online how to create custom routed events.

Take a look at this code:

// This event uses the bubbling routing strategy 
public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
    "Tap", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TCardView));

// Provide CLR accessors for the event 
public event RoutedEventHandler Tap
{
        add { AddHandler(TapEvent, value); } 
        remove { RemoveHandler(TapEvent, value); }
}

// This method raises the Tap event 
void RaiseTapEvent()
{
        RoutedEventArgs newEventArgs = new RoutedEventArgs(TCardView.TapEvent);
        RaiseEvent(newEventArgs);
}

public TCardBase SelectedTCard
{
    get { return (TCardBase)GetValue(SelectedTCardProperty); }
    set { SetValue(SelectedTCardProperty, value); }
}

// Using a DependencyProperty as the backing store for SelectedTCard.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedTCardProperty =
    DependencyProperty.Register("SelectedTCard", typeof(TCardBase), typeof(TCardView), new PropertyMetadata(SelectedTCardPropertyChanged));


private static void SelectedTCardPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
    ((TCardView)o).RaiseTapEvent();
}

Try it out. :)

Upvotes: 1

Related Questions