2010-03-30 47 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

相关问题