user652644
user652644

Reputation: 3

Bind Events to UserControl in WPF

How can i propagate the PreviewKeyDown event out from the myUserControl which is inside a myWindow.

in myWindow.xaml

<local:MyFilter x:Name="check" MyEvent="submit" />

in myUserContorl.xaml

   <ComboBox x:Name="combo" PreviewKeyDown="{Binding Path=MyEvent}" />

in myUserContorl.xaml.cs

#region MyEvent

    /// <summary>
    /// Gets or sets the Label which is displayed next to the field
    /// </summary>
    public EventHandler MyEvent
    {
        get { return (EventHandler)GetValue(EventHandlerProperty); }
        set { SetValue(EventHandlerProperty, value); }
    }

    /// <summary>
    /// Identified the Label dependency property
    /// </summary>
    public static readonly DependencyProperty EventHandlerProperty =
        DependencyProperty.Register("MyEvent", typeof(EventHandler),
          typeof(myUserControl), new PropertyMetadata(""));

    #endregion

This works for just 'string fields' like content or text... but doesn't work for events

Upvotes: 0

Views: 82

Answers (1)

Clemens
Clemens

Reputation: 128137

Just add (and remove) event handlers to the underlying control:

public event KeyEventHandler MyEvent
{
    add { combo.AddHandler(PreviewKeyDownEvent, value); }
    remove { combo.RemoveHandler(PreviewKeyDownEvent, value); }
}

without any Binding in XAML:

<ComboBox x:Name="combo" />

Upvotes: 1

Related Questions