微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Implementing your own base class for user controls in Silverlight 2

The objective is to create your own base class for user controls to implement application related features and at the same time also use the features provided by the Visual Studio (i.e. auto generate a partial class that initialize all UI elements).

The process can be described best with three projects:

 

For the sake of simplicity I created a simple UserControlBase class extending from the UserControl class. This calss can contain the common methods and properties as needed for your application. Here I have added some dummy methods and properties.

  1. namespace BaseLibrary
  2. {
  3.     public class UserControlBase : UserControl
  4.     {
  5.         public int Id { getset; }
  6.         public void DoSomeThing()
  7.         {
  8.             //...
  9.         }
  10.     }

Then,lets create a TestControl class and a TestControl.xaml in the class library where we like the have the custom controls:

  1. namespace CustomControls
  2. {
  3.     public partial class TestControl : UserControlBase
  4.     {
  5.         public TestControl()
  6.         {
  7.             InitializeComponent();
  8.         } 
  9.     }

Now,here is the trick. Look closely to the xaml. Instead of regular UserControl, we used our own base class. To do so,we also have to include the namespace.

  1. <bl:UserControlBase x:Class="MyControls.TestControl"
  2.     xmlns="http://schemas.microsoft.com/client/2007"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     xmlns:bl="clr-namespace:BaseLibrary;assembly=BaseLibrary"
  5.     Width="150" Height="50">
  6.     <Grid Background="LightCoral">
  7.         <TextBlock Text="I am a test control"/>
  8.     </Grid>
  9. </bl:UserControlBase> 

In this way,Visual Studio also generates the partial class properly. But there is one side effect: the Visual Studio will not be able to show you the UI preview in designer. I haven't found any work around yet.

 

Update:

I forgot to add the reference in AsseblyInfo.cs file of BaseLibrary project. Once you add the following reference the Visual Studio will render the UI properly. Thanks to Michael for pointout the issue.

 

[assembly: XmlnsDeFinition("http://schemas.microsoft.com/client/2007","BaseLibrary")] 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐