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.
- namespace BaseLibrary
- {
- public class UserControlBase : UserControl
- {
- public int Id { get; set; }
- public void DoSomeThing()
- {
- //...
- }
- }
- }
Then,lets create a TestControl class and a TestControl.xaml in the class library where we like the have the custom controls:
- namespace CustomControls
- {
- public partial class TestControl : UserControlBase
- {
- public TestControl()
- {
- InitializeComponent();
- }
- }
- }
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.
- <bl:UserControlBase x:Class="MyControls.TestControl"
- xmlns="http://schemas.microsoft.com/client/2007"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:bl="clr-namespace:BaseLibrary;assembly=BaseLibrary"
- Width="150" Height="50">
- <Grid Background="LightCoral">
- <TextBlock Text="I am a test control"/>
- </Grid>
- </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 举报,一经查实,本站将立刻删除。