在WPF中将事件绑定到UserControl

时间:2017-08-31 17:57:07

标签: c# wpf xaml

如何从myWserow内部的myUserControl传播PreviewKeyDown事件。

myWindow.xaml中的

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

在myUserContorl.xaml

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

在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

这适用于内容或文字等“字符串字段”......但不适用于事件

1 个答案:

答案 0 :(得分:1)

只需将事件处理程序添加(并删除)到基础控件:

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

在XAML中没有任何绑定:

<ComboBox x:Name="combo" />