2009-08-17 147 views
5

如何創建一個事件來處理來自我的自定義控件的其他控件之一的單擊事件?Silverlight自定義控件創建自定義事件

這裏是我有什麼設置: 一個文本框和一個按鈕(自定義控件) Silverlight應用程序(使用上面的自定義控制)

我想揭露的單擊事件按鈕從主應用程序的自定義控件上,我該怎麼做?

感謝

+0

您的自定義控件是用戶控件(來自UserControl)還是一個真正的控件?您應該能夠在文件後面的代碼中公開事件,並將其附加到您的子控件的事件以便展示事件。 – 2009-08-17 22:51:11

+0

他們是2個真正的控制合併爲1,我只是想暴露按鈕的點擊事件。 當我在用戶控件上工作時,我可以進入點擊事件,但是如果我正在處理某些使用用戶控件的事件,那麼我將無法訪問該事件處理程序。 – PlayKid 2009-08-18 05:53:07

回答

8

這裏是一個超級簡單的版本,因爲我沒有使用依賴屬性或任何東西。它會公開Click屬性。這假設按鈕模板部分的名稱是「按鈕」。

using System.Windows; 
using System.Windows.Controls; 

namespace SilverlightClassLibrary1 
{ 
    [TemplatePart(Name = ButtonName , Type = typeof(Button))] 
    public class TemplatedControl1 : Control 
    { 
     private const string ButtonName = "Button"; 

     public TemplatedControl1() 
     { 
      DefaultStyleKey = typeof(TemplatedControl1); 
     } 

     private Button _button; 

     public event RoutedEventHandler Click; 

     public override void OnApplyTemplate() 
     { 
      base.OnApplyTemplate(); 

      // Detach during re-templating 
      if (_button != null) 
      { 
       _button.Click -= OnButtonTemplatePartClick; 
      } 

      _button = GetTemplateChild(ButtonName) as Button; 

      // Attach to the Click event 
      if (_button != null) 
      { 
       _button.Click += OnButtonTemplatePartClick; 
      } 
     } 

     private void OnButtonTemplatePartClick(object sender, RoutedEventArgs e) 
     { 
      RoutedEventHandler handler = Click; 
      if (handler != null) 
      { 
       // Consider: do you want to actually bubble up the original 
       // Button template part as the "sender", or do you want to send 
       // a reference to yourself (probably more appropriate for a 
       // control) 
       handler(this, e); 
      } 
     } 
    } 
}