运行环境: Silverlight 3.0(未在2.0下面做过测试,貌似本方法不支持2.0,因为2.0下面,ResourceDictionary没有Source属性)

ResourceDictionary resources = new ResourceDictionary();
resources.Source 
= new Uri("/Cinlap.UI.SL.Controls;component/Themes/Generic.xaml", System.UriKind.Relative);

ControlTemplate controlTemplate 
= resources[templateName] as ControlTemplate;

只要将ResourceDictionary.Source属性设置为合适的Uri,则可以通过Key来获取需要的对象。

补充:刚才又发现一个利用ResourceDictionary的场景
在创建自定义控件时,我们有可能需要在Generic.xaml中定义多个控件的Style,定义的多了找起来就很麻烦,如果在单个文件里定义好,然后在Generic.xaml中包含(include)岂不是很好,看到了Telerik.RedControl For Silverlight中使用了<?include(***.xaml)?>式语句,但始终没有找到如何实现该功能,无奈,只得找其他的方式,终于发现使用ResourceDictionary.Source也能实现同样功能,Generic.xaml代码如下:

<ResourceDictionary
    
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml">

    
<ResourceDictionary.MergedDictionaries>
        
<ResourceDictionary Source="/Cinlap.UI.SL.Controls;component/Themes/DockPanel.xaml"/>
    
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

显而易见,此方法也是在一个xaml文件中包含另一个xaml文件的方法。
posted on 2009-08-09 21:10  think8848  阅读(1864)  评论(1编辑  收藏  举报