2010-03-30 53 views
2

將我自己的屬性添加到現有Silverlight控件的最佳方式是什麼?例如,我想將自定義類與DataGrid關聯,並且能夠在Expression Blend中設置此自定義類的屬性?向Silverlight控件添加自定義屬性

這是一件容易的事情嗎?

感謝,

AJ

回答

1

通過繼承,這是很容易做到的。

這是例如一個數據網格,它在輸入擊鍵時觸發一個驗證事件。

namespace SLCommon 
{ 
    public delegate void VaditateSelectionEventHandler(object sender, EventArgs e); 

    /// <summary> 
    /// Fires a validate event whenever the enter key or the left mouse button is pressed 
    /// </summary> 
    public class EventDatagrid : DataGrid 
    { 
     public event VaditateSelectionEventHandler Validate; 

     public EventDatagrid() 
      : base() 
     { 
      this.MouseLeftButtonUp += new MouseButtonEventHandler(OnMouseLeftButtonUp); 
     } 

     protected override void OnKeyDown(KeyEventArgs e) 
     { 
      if (e.Key != Key.Enter) 
       base.OnKeyDown(e); 
      else 
      { 
       e.Handled = true; 
       Validate(this, e); 
      } 
     } 

     protected void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) 
     { 
      Validate(this, e); 
     } 
    } 
} 

XAML的一面:

<slc:EventDatagrid x:Name="toto" Validate="toto_Validate" 
          AutoGenerateColumns="True" IsReadOnly="True" Width="auto" MaxHeight="300"> 
</slc:EventDatagrid> 

注意驗證事件處理程序。

在這裏,您可以在xaml文件中添加一個控件myobj(確保在頁面頂部聲明正確的xmlns:名稱空間)並設置它的屬性。

不知道混合,但它確實以同樣的方式工作。

+0

你好,你居然這樣做呢?我的印象是,Silverlight控件的子類在運行時無法初始化。 – 2010-03-30 11:28:54

+0

是的,我已經做了很多次了。你想要一個生動的例子嗎? – Vinzz 2010-03-30 11:36:49

+0

它的工作原理非常感謝。但是,如果您執行Google搜索,則會提到各種問題。早期版本的SL沒有這種能力嗎? – 2010-03-30 12:16:24

相關問題