[Silverlight] 改进 Nikhil Kothari 的换肤方案:允许自定义控件的皮肤定义

Silverlight 下换肤的实现 中,我介绍了 Nikhil Kothari 实现的一种 Theme 方案。但是实践了一下,我很快发现有个小小的缺陷。作者的皮肤定义是仅针对系统自带的控件的,如 Button, TextBox, CheckBox 等,而对于我们自定义的控件的换肤问题没有很好的解决。从下列代码中可见一斑:

(/Framework/Applications/Theme.cs)
public string GetXml() {
    
string resourceDictionaryFormat =
@"<UserControl 
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:vsm=""clr-namespace:System.Windows;assembly=System.Windows"">
<UserControl.Resources>
{0}
</UserControl.Resources>
</UserControl>
";

    _content.Replace(
@"xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""""");
    _content.Replace(
@"xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""""");
    _content.Replace(
@"xmlns:vsm=""clr-namespace:System.Windows;assembly=System.Windows""""");

    
return String.Format(resourceDictionaryFormat, _content.ToString());
 }

可以看出这里名称空间都是写死了的,不支持任何扩展。
而实际使用中,我们可能会对某个第三方控件定义样式。比如:

<UserControl
    
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d
="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc
="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:liquid
="clr-namespace:Liquid;assembly=Liquid"
    mc:Ignorable
="d"
    x:Class
="UserControl"
    d:DesignWidth
="640" d:DesignHeight="480">
    
<UserControl.Resources>
        
<Style x:Key="MyLiquidDialog" TargetType="liquid:Dialog">
            
<!-- 略 -->
        
</Style>    
    
</UserControl.Resources>

    
<Grid x:Name="LayoutRoot" Background="White" />
</UserControl>

这里定义了 Liquid 这套组件中 Dialog 控件的样式,而其中 xmlns:liquid 这个名称空间的声明就是必须的。

要达到这个目标,我们可以修改 Theme.cs 的 parse 步骤,在其过程中补充一段收集 xml namespace 的代码,并在合并最终的样式 xaml 时加进去即可。

修改过的 Theme.cs 代码如下:

修改过的 Theme.cs


其中灰色部分是主要修改的代码。这样改过后,重新编译 Nikhil Kothari 的 Framework 项目,并把生成的 dll 引用到自己项目中即可支持第三方控件的换肤了。

修改过的 DLL [下载]





posted on 2008-07-17 14:02  NeilChen  阅读(2843)  评论(2编辑  收藏  举报

导航