Implementing your own base class for user controls in Silverlight 2

來源:互聯網
上載者:User

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 { get; set; }
  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")] 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.