Freigeben über


Basics of Custom Control in Silverlight

At MIX lot of people were asking about where the controls were. I have also seen the blogs posts where some people have mistakenly equate not having canned controls to not being able to build control. It is true that we don't have any in build control as part of the core runtime in the Alpha bits. We do have sample control pack that includes Button, ListBox, ScrollViewer, Slider. We deliberately focused on ability to create custom controls for this version rather than having traditional control set because we felt that it would give more flexibility to developers as people will be able to do more stuff with the platform. Building a custom control itself is fairly straight forward process.

Here is the simple version of how to build control...

  • Create a class that inherits from base "Control" class that is now part of V1.1 alpha

The most important part of this class is method called "InitializeFromXaml". This methods takes a XAML in string form and creates a tree. you can generate this string in variety of different way such as embedding XAML in the assembly (default VS behavior), download XAML from web server or generate XAML on the fly.

Offcouse you can generate the same tree by constructing various objects in code but then you lose the ability to tweak the looks of that XAML in Expression Blend. IntializeFromXaml also turns on namescoping so you can instantiate same control multiple times on the given page and element names don't conflict.

This defines the look of the control.

  • Implement you control specific methods/properties/events.

This is no different than building controls in any other platform. This methods/properties/events define the "Custom" part of the custom control. Button has Click Event or Slider has ValueChanged event. Button has Text property or Slider has TickFrequency property etc.

This define the behavior as well as API exposure of the control.

  • Use the control in your application page

Since custom controls are expressed as custom tags in XAML, you also need to tell XAML parser where to find those controls so that parser can  instantiate them when it encounters them in XAML.

This is done using syntax as follows

 xmlns:Custom="clr-namespace:SPFControls;assembly=ClientBin/Slider.dll"

then you use actual control as follows...

 <Custom:Slider Height="50" Width="500" 

When parser tries to instantiate Slider element, it finds the slider element in ClientBin/Slider.dll. It also tells parser that class mapping to that element exists in the SPFControls namespace within that assembly.

Comments