Benutzer:MovGP0/WPF/Routed Events

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


Handling Routed Event

[Bearbeiten | Quelltext bearbeiten]
<Window (...) ButtonBase.Click="OnWindowClick">
    <StackPanel ButtonBase.Click="OnStackPanelClick">
        <Button Click="OnButtonClick" Content="Click me" />
    </StackPanel>
</Window>

Handling handeled Routing Event

[Bearbeiten | Quelltext bearbeiten]
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

[Bearbeiten | Quelltext bearbeiten]
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

[Bearbeiten | Quelltext bearbeiten]
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);
}