我有一个带有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方法;第一个在赋值操作发生时触发,但第二个不触发。
看到我做错了什么吗?您已经在UniformGrid
上注册了您的依赖属性以设置处理程序,您需要一个UniformGrid实例和以下代码:
uniformGrid.SetValue(MyUserControl.GridButtonClickHandlerProperty, new RoutedEventHandler(btn_clicked));
如果它不是你的目标,并想使用它:numpad.GridButtonClickHandler += btn_clicked;
,其中numpad是你的用户控制。那么owner类型应该是注册时的用户控件:
public static readonly DependencyProperty GridButtonClickHandlerProperty =
DependencyProperty.Register ( "GridButtonClickHandler",
typeof ( RoutedEventHandler ),
typeof ( MyUserControl),
new PropertyMetadata ( GridButtonClickPropertyChanged ) );
你需要一个路由事件,而不是一个依赖属性…
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));
}