views:

75

answers:

2

Hello,

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 set the properties of this custom class in Expression Blend?

Is this an easy thing to do?

Thanks,

AJ

+1  A: 

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.

Vinzz
Hello, have you actually done this? I was under the impression that subclassed Silverlight controls fail to initialize at runtime.
AJ
yes, I've done this, and many times, at that. Do you want a live example?
Vinzz
It works, thank you very much. But if you do a Google search then all sorts of problems are mentioned. Did earlier versions of SL not have this ability?
AJ
indeed, it's apain to deal with Silverlight 3, because every search you make returns results about a bug or a missing feature in SL2 beta or SL1 ...
Vinzz
A: 

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

JerKimball