Implementing your own base class for user controls in Silverlight 2

本文介绍如何创建一个自定义的用户控件基类,该基类继承自UserControl,并可在其中实现应用程序特有的功能,同时利用Visual Studio自动生成初始化所有UI元素的部分类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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")] 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值