2011-12-12 30 views
0

我有一個用戶控件與一個UniformGrid有一些按鈕。我想爲每個Button的Click事件分配相同的處理程序。所以,添加以下到用戶控件:DependencyProperty PropertyChangedCallback接線

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方法;第一次擊中分配發生時,但第二次未擊中。

看看我做錯了什麼?

+0

我想也許最後的引用應該是numpad.GridButtonClickHandler = btn_clicked,但那也沒有工作。 –

回答

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)); 
+0

這是我搞砸了的Register typeof(MyUserControl)。謝謝! –

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)); 
} 
相關問題