【问题标题】:DependencyProperty PropertyChangedCallback wiringDependencyProperty PropertyChangedCallback 接线
【发布时间】:2011-12-12 16:23:05
【问题描述】:

我有一个带有多个按钮的 UniformGrid 用户控件。我想为每个按钮的 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.GridButtonClickHandler += btn_clicked;

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

看看我做错了什么?

【问题讨论】:

  • 我想也许最后一个引用应该是 numpad.GridButtonClickHandler = btn_clicked,但这也没有用。

标签: wpf .net-3.0


【解决方案1】:

您已经在 UniformGrid 上注册了您的依赖属性,以便为它设置一个处理程序,您需要一个 UniformGrid 实例和以下代码:

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

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

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

【讨论】:

  • 这是我搞砸的Register typeof (MyUserControl)。谢谢!
【解决方案2】:

你需要一个路由事件,而不是依赖属性...

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));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多