开发者

Adding custom properties to Silverlight controls

What is the best way for me to add my own properties to an existing Silverlight control? For example I would like to associate a custom class with the DataGrid and be able to s开发者_如何学JAVAet the properties of this custom class in Expression Blend?

Is this an easy thing to do?

Thanks,

AJ


By inheritance, it's pretty easy to do.

Here's for example a datagrid that triggers a validate event on enter keystroke.

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 side:

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

Note the Validate event handler.

Here after you can add a control myobj in a xaml file (be sure to declare the right xmlns: namespace on the top of your page) and set it's property.

Don't know about blend, but it sure works the same way.


Another option would be to use an attached behavior/property. It's the inheritance/composition argument - to extend functionality of class X, do you inherit from class X and extend it, or do you create class Y that contains class X?

Here's an example of someone adding PixelSnapping to SL via attached behavior: http://blogs.msdn.com/devdave/archive/2008/06/22/Using-an-Attached-DependencyProperty-to-Implement-Pixel-Snapping-as-an-Attached-Behavior.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜