Benutzer:MovGP0/WPF/Routed Events

aus Wikipedia, der freien Enzyklopädie
< Benutzer:MovGP0‎ | WPF
Dies ist die aktuelle Version dieser Seite, zuletzt bearbeitet am 27. Dezember 2015 um 15:10 Uhr durch imported>MovGP0(77247) (→‎Handling Routed Event).
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


Routed Events

Handling Routed Event

<Window (...) ButtonBase.Click="OnWindowClick">
    <StackPanel ButtonBase.Click="OnStackPanelClick">
        <Button Click="OnButtonClick" Content="Click me" />
    </StackPanel>
</Window>

Handling handeled Routing Event

public MainWindow()
{
    InitializeComponent();
    AddHandler(ButtonBase.ClickEvent, newRoutedEventHandler(OnWindowClick), // registering handler globally
        handeled: true); // handle handeled events too
}

private void OnButtonClick(object sender, RoutedEventArgs e)
{
    e.Handeled = true; // prevents bubbling
}

private void OnWindowClick(object sender, RoutedEventArgs e)
{

}

Custom Routed Event

public satic readonly RoutedEvent ClickEvent = 
    EventManager.RegisterRoutedEvent(nameof(Click), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyControl)); 

public event RoutedEventHandler Click
{
    add{ AddHandler(ClickEvent, value); }
    remove { RemoveHandler(ClickEvent, value); }
}

private void RaiseClickEvent()
{
    var args = new RoutedEventArgs(MyControl.ClickEvent);
    RaiseEvent(args);
}

Custom MyRoutedEventHandler/RoutedEventArgs

public sealed class MyRoutedEventArgs : RoutedEventArgs
{
    public MyRoutedEventArgs (RoutedEvent routedEvent, string param) : base(routedEvent)
    {
        Param = param;
    }

    public string Param { get; }
}

public delegate void MyRoutedEventHandler(object sender, MyRoutedEventArgs e);
usage
public satic readonly RoutedEvent ClickEvent = 
    EventManager.RegisterRoutedEvent(nameof(Click), RoutingStrategy.Bubble, typeof(MyRoutedEventHandler), typeof(MyControl)); 

public event MyRoutedEventHandler Click
{
    add{ AddHandler(ClickEvent, value); }
    remove { RemoveHandler(ClickEvent, value); }
}

private void RaiseClickEvent()
{
    var args = new MyRoutedEventArgs(MyControl.ClickEvent, "Hello World!");
    RaiseEvent(args);
}