WPF将函数注册为依赖属性

本文关键字:依赖 属性 注册 函数 WPF | 更新日期: 2023-09-27 18:25:36

我仍在学习wpf,我正在尝试创建自己的控件,但我在将函数注册为dependencyProperty 时遇到了问题

假设我有我的控件,我希望用户为我的控件的OnChange事件指定一个函数,我尝试了以下

    public readonly static DependencyProperty OnChangeProperty;
    public delegate void DependencyPropertyChangedEventHandler(Object sender, DependencyPropertyChangedEventArgs e);
    public DependencyPropertyChangedEventHandler Change;

    OnChangeProperty = DependencyProperty.Register("OnChange", typeof(DependencyPropertyChangedEventHandler), typeof(MyControl), new FrameworkPropertyMetadata(null));
    public DependencyPropertyChangedEventHandler OnChange
    {
        get { return (DependencyPropertyChangedEventHandler)GetValue(OnChangeProperty); }
        set { SetValue(OnChangeProperty, value); }
    }
    <my:MyControl OnChange="Control_OnChange"/>

但它没有起作用,当它遇到"Control_OnChange"时,它会给我一个XAML解析异常,有人能给我指明正确的方向吗?我在MSDN上找不到这个问题的答案,所以,我是不是遗漏了什么?

WPF将函数注册为依赖属性

不能将函数注册为依赖属性。您应该创建一个自定义路由事件:

// Register the routed event
public static readonly RoutedEvent SelectedEvent = 
EventManager.RegisterRoutedEvent( "Selected", RoutingStrategy.Bubble, 
typeof(RoutedEventHandler), typeof(MyCustomControl));
// .NET wrapper
public event RoutedEventHandler Selected
{
    add { AddHandler(SelectedEvent, value); } 
    remove { RemoveHandler(SelectedEvent, value); }
}

然后您可以在UserControl:中提出该事件

// Raise the routed event "selected"
RaiseEvent(new RoutedEventArgs(MyCustomControl.SelectedEvent));

然后您可以向事件添加一个处理程序:

<my:MyCustomControl Selected="Control_OnSelected"/>