Mar*_*ram 17 inheritance xaml user-controls silverlight-2.0
如果我有一个我编写的usercontrol(在Silverlight中),它使用XAML来定义它的外观,我该如何制作它的自定义版本?
即我有MyControl.xaml和MyControl.xaml.cs
如果我想要一个"SpecialisedControl"子类,我该怎么办?我假设我只是创建一个新的代码文件,然后从MyControl继承.但是,如果我想改变基类的外观,那该怎么办?
我写这篇文章的时候认为你是在讨论WPF,而不是Silverlight,但可能有足够的重叠让这对你有所帮助,所以无论如何我都会发布它.
如果通过"更改基类的外观"意味着"提供新模板",那么您需要的可能是CustomControl,而不是UserControl.
完成此操作的最佳方法是按照其他Microsoft控件设置的示例,例如Button或ListBox:
这肯定比简单地从UserControl派生更多的工作,但如果你想能够完全重新模板控件,就像你可以使用内置控件一样,这就是这样做的方法.
另一方面,如果您要做的只是提供一定数量的有限自定义,例如更改背景,或将Command与某些用户操作相关联,那么最好的办法是公开DependencyProperties,然后可以可以为您的控件或控件实例设置样式.
如果您提到要在继承的控件中自定义外观,则该过程非常相似:只需使用新模板为新控件添加默认样式; 如果您需要添加更多事件处理程序,请绝对确定您调用base.OnApplyTemplate().
小智 5
我不知道,我喜欢用普通物体做事.这篇文章描述了一种简单的方法,可以将XAML设计的控件放在继承层次结构之外,这样您就可以使用SimpleThingsLikeInheritance而不是MicrosoftStuffThatAlmostWorks来自定义外观和行为.
http://gen5.info/q/2009/02/10/subverting-xaml-how-to-inherit-from-silverlight-user-controls/
正如Mihnea的链接所描述的,最简单的解决方案是在XAML中简单地添加命名空间:
public class MyBase : UserControl
{
}
public class FirstUserControl : MyBase
{
...
}
Run Code Online (Sandbox Code Playgroud)
<local:MyBase
x:Class="FirstUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="YourAssembly" ...>
<!-- Sticking with UserControl instead of local:MyBase makes this clearer -->
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
..
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
..Your XAML
</local:MyBase>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25994 次 |
最近记录: |