DependencyProperty PropertyChangedCallback接线

时间:2011-12-12 16:23:05

标签: wpf .net-3.0

我有一个具有许多按钮的UniformGrid的用户控件。我想为每个Button的Click事件分配相同的处理程序。所以,我在用户控件中添加了以下内容:

    public RoutedEventHandler GridButtonClickHandler
    {
        get { return ( RoutedEventHandler ) GetValue ( GridButtonClickHandlerProperty ); }
        set { SetValue ( GridButtonClickHandlerProperty, value ); }
    }

    public static readonly DependencyProperty GridButtonClickHandlerProperty =
        DependencyProperty.Register ( "GridButtonClickHandler", typeof ( RoutedEventHandler ), typeof ( UniformGrid ),
            new PropertyMetadata ( GridButtonClickPropertyChanged ) );

    private static void GridButtonClickPropertyChanged ( DependencyObject o, DependencyPropertyChangedEventArgs e )
    {
        ( ( UniformGrid ) o ).Children.OfType<Button> ( ).ToList ( ).ForEach ( b => b.Click += ( RoutedEventHandler ) e.NewValue );
    }

然后,在某个地方存在对用户控件的引用(本例中为numpad),我有这个:

numpad.GridButtonClickHandler += btn_clicked;

我在GridButtonClickHandler集和GridButtonClickPropertyChanged方法中有断点;分配发生时的第一次命中,但第二次命中率从未命中。

看看我做错了什么?

2 个答案:

答案 0 :(得分:1)

您已在UniformGrid上注册了依赖项属性以设置处理程序,您需要UniformGrid实例和以下代码:

uniformGrid.SetValue(MyUserControl.GridButtonClickHandlerProperty, new RoutedEventHandler(btn_clicked));

如果这不是您的目标并且想要使用它:numpad.GridButtonClickHandler += btn_clicked;其中numpad是您的用户控件。然后,在注册期间,所有者类型应该是您的用户控件:

public static readonly DependencyProperty GridButtonClickHandlerProperty =
        DependencyProperty.Register ( "GridButtonClickHandler", 
        typeof ( RoutedEventHandler ), 
        typeof ( MyUserControl),
            new PropertyMetadata ( GridButtonClickPropertyChanged ) );

答案 1 :(得分:0)

您需要路由事件,而不是依赖属性...

public static readonly RoutedEvent GridButtonClickEvent = EventManager.RegisterRoutedEvent("GridButtonClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl));

public event RoutedEventHandler GridButtonClick
{
    add { AddHandler(GridButtonClickEvent, value); }
    remove { RemoveHandler(GridButtonClickEvent, value); }
}

单击按钮时,举起事件:

private void GridButton_Click(object sender, RoutedEventArgs e)
{
    RaiseEvent(new RoutedEventArgs(GridButtonClickEvent, this));
}