这次给大家晒晒 silverlight 用户控件的另一种写法xamlreader.
是不是有些朋友想过在 silverlighter 里使用 aps.net 里面的 response.write(); 方法输出HTML代码那样输出 XAML 代码呢? 呵呵这里我就给大家晒晒如何实现吧~
首先我要帮大家引入一个对象 他位置与 System.Windows.Markup; 命名空间下. 这里有一个静态类XamlReader,以及read方法 我们就要用他来创建我们的usercontrol.
- // Summary:
- // Provides a XAML processor engine for parsing XAML and creating corresponding
- // Silverlight object trees.
- public static class XamlReader
- {
- // Summary:
- // Parses a well-formed XAML fragment and creates a corresponding Silverlight
- // object tree, and returns the root of the object tree.
- //
- // Parameters:
- // xaml:
- // A string that contains a valid XAML fragment.
- //
- // Returns:
- // The root object of the Silverlight object tree.
- public static object Load(string xaml);
了解这个对象后给大家一个实例看看怎么用吧~ 还是很简单的,
1. 我们创建一个类 自然就是我们的 usercontrol 了 继承自 control
2. 我们要把我们模板的 Xmal 以string 的形式保存写入程序中
3. 我们要在构造函数中载入这些 XAML
4. 我们在重载onapplytemplate() 方法中声明创建的对象XMAL代码.
以下是我要写入的Xaml;
- public class MyImage : Control
- {
- Image _myImage = null;
- private const string _contentTemplate
- = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" +
- "xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">" +
- "<Image x:Name=\"sonicImage\" Source=\"space.jpg\"></Image>" +
- "</ControlTemplate>";
- }
构造函数
- public MyImage()
- {
- Template = (ControlTemplate)XamlReader.Load(_contentTemplate);
- ApplyTemplate();
- }
重载onapplytemplate
- public override void OnApplyTemplate()
- {
- _myImage = (Image)GetTemplateChild("sonicImage");
- }
这样我们就可以更灵活的使用我们的用户控件,很简单吧~ 希望这点技巧对你有所帮助^^
Source code: XamlReader_Demo
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。