`
jiasongmao
  • 浏览: 661202 次
  • 性别: Icon_minigender_1
  • 来自: 石家庄
社区版块
存档分类
最新评论

silverlight中如何把UIElement等对象转换为xaml字符串

阅读更多

silverlight类库中没有提供,在网上找了找,貌似资料很少。现把我找到的一个并做了小量的修改,现拿出来分享一下:

总共分为两个类:XamlHelper和XamlWriter。

 

XamlHelper.cs

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Reflection;
using System.Text.RegularExpressions;

namespace SARuntimeXAMLWriter
{
    internal class XamlHelper
    {
        internal static bool hasCollections(DependencyObject obj)
        {
            PropertyInfo[] props = obj.GetType().GetProperties();
            foreach (var prop in props)
                if (prop.Name != "Parent" && (prop.PropertyType.BaseType.Name == "Collection`1" || prop.PropertyType.Name == "Transform"))
                    return true;
            return false;
        }
        internal static bool hasDeepCollections(DependencyObject obj, PropertyInfo prop)
        {
            if (obj == null || prop.PropertyType.IsArray)
                return false;
            return ((prop.GetValue(obj, null) ?? new object()).ToString().StartsWith("System."));
        }
        internal static string getSilverlightCompatibleXaml(string xaml)
        {
            Regex reg = new Regex(@"(\<(/)?\w+\.Children\>)", RegexOptions.None);
            return reg.Replace(xaml, "").Replace("xName", "x:Name");
        }
    }
}

 

XamlWriter.cs

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Reflection;
using System.Text;
using System.Xml;

namespace SARuntimeXAMLWriter
{
    public class XamlWriter
    {
        public static string Write(DependencyObject parent)
        {
            StringBuilder sb = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(sb, settings);
            //if (!TypeValidator.isValid(parent))
            //    throw new TypeValidationException();
            writer.WriteStartElement(parent.GetType().Name);
            writeCLRProperties(parent, writer);
            writeDPs(parent, writer);
            writeBrushes(parent, writer);
            writeCollections(parent, writer);
            writer.WriteEndElement();
            writer.Flush();
            writer.Close();
            return XamlHelper.getSilverlightCompatibleXaml(sb.ToString());
        }
        private static void writeCLRProperties(DependencyObject target, XmlWriter writer)
        {
            PropertyInfo[] props = target.GetType().GetProperties();
            bool hdc = false;
            foreach (var prop in props)
            {
                hdc = XamlHelper.hasDeepCollections(target, prop);
                if (prop.Name == "Name")
                {
                    if (prop.GetValue(target, null).ToString() != "")
                        writer.WriteAttributeString("x" + prop.Name, prop.GetValue(target, null).ToString());
                }
                else if (prop.Name != "Parent" && prop.CanRead && prop.CanWrite && prop.GetValue(target, null) != null
                    && prop.PropertyType.BaseType.Name != "Collection`1" && prop.PropertyType.Name != "Brush"
                    && !hdc)
                {
                    var propValue = prop.GetValue(target, null).ToString();
                    if (!propValue.Equals("Infinity") && !propValue.Equals("NaN"))
                        writer.WriteAttributeString(prop.Name, prop.GetValue(target, null).ToString());
                }
            }
        }
        private static void writeDPs(DependencyObject target, XmlWriter writer)
        {
            //DPs problem
            try
            {
                writer.WriteAttributeString("Canvas.Left", target.GetValue(Canvas.LeftProperty).ToString());
                writer.WriteAttributeString("Canvas.Top", target.GetValue(Canvas.TopProperty).ToString());
                writer.WriteAttributeString("Canvas.ZIndex", target.GetValue(Canvas.ZIndexProperty).ToString());
            }
            catch { }
            try
            {
                writer.WriteAttributeString("Storyboard.TargetName", target.GetValue(Storyboard.TargetNameProperty).ToString());
                writer.WriteAttributeString("Storyboard.TargetProperty", target.GetValue(Storyboard.TargetPropertyProperty).ToString());
            }
            catch { }

        }
        private static void writeBrushes(DependencyObject target, XmlWriter writer)
        {
            PropertyInfo[] props = target.GetType().GetProperties();
            object val;
            foreach (var prop in props)
                if (prop.PropertyType.Name == "Brush" && (val = prop.GetValue(target, null) ?? new object()).ToString() != "")
                {
                    if (val.ToString() == "System.Object")
                        continue;
                    writer.WriteStartElement(prop.ReflectedType.Name + "." + prop.Name);
                    writer.WriteStartElement(val.ToString().Split('.')[3]);
                    writeCLRProperties((DependencyObject)val, writer);
                    writeDeepCollections((DependencyObject)val, writer);
                    writeCollections((DependencyObject)val, writer);
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }
        }
        private static void writeCollections(DependencyObject target, XmlWriter writer)
        {
            if (target == null)
                return;
            PropertyInfo[] props = target.GetType().GetProperties();
            int cnt;
            object val;
            string collectionElement = "";
            foreach (var prop in props)
                if (prop.Name != "Parent" && prop.PropertyType.BaseType != null && prop.PropertyType.BaseType.Name == "Collection`1")
                {
                    cnt = (int)prop.PropertyType.InvokeMember("get_Count", BindingFlags.InvokeMethod, null, prop.GetValue(target, null), null);
                    for (int i = 0; i < cnt; i++)
                    {
                        val = prop.PropertyType.InvokeMember("get_Item", BindingFlags.InvokeMethod, null, prop.GetValue(target, null), new object[] { i });
                        if (XamlHelper.hasCollections((DependencyObject)val))
                        {
                            if (collectionElement != prop.ReflectedType.Name + "." + prop.Name)
                            {
                                if (collectionElement != "")
                                    writer.WriteEndElement();
                                collectionElement = prop.ReflectedType.Name + "." + prop.Name;
                                writer.WriteStartElement(collectionElement);
                            }
                            writer.WriteStartElement(val.GetType().Name);
                            writeCLRProperties((DependencyObject)val, writer);
                            writeDPs((DependencyObject)val, writer);
                            writeBrushes((DependencyObject)val, writer);
                            writeCollections((DependencyObject)val, writer);
                            writer.WriteEndElement();
                        }
                        else
                        {
                            writer.WriteStartElement(val.GetType().Name);
                            writeCLRProperties((DependencyObject)val, writer);
                            writeDPs((DependencyObject)val, writer);
                            writeBrushes((DependencyObject)val, writer);
                            writeDeepCollections((DependencyObject)val, writer);
                            writer.WriteEndElement();
                        }
                    }
                    if (collectionElement != "")
                    {
                        writer.WriteEndElement();
                        collectionElement = "";
                    }
                }
                //TransformGroup not inherits from Collection, so it can not be added
                //through writeCollections/writeDeepCollections and we should handle
                //it separately
                else if (prop.PropertyType.Name == "Transform")
                {
                    val = prop.GetValue(target, null);
                    if (val == null)
                        continue;
                    if (val.GetType().ToString() != "System.Windows.Media.TransformGroup" ||
                        ((int)val.GetType().GetProperty("Children").GetValue(val, null).GetType().GetProperty("Count").GetValue(val.GetType().GetProperty("Children").GetValue(val, null), null)) == 0)
                        continue;
                    writer.WriteStartElement(prop.ReflectedType.Name + "." + prop.Name);
                    writer.WriteStartElement(val.GetType().Name);
                    writeCollections(val as DependencyObject, writer);
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }
        }
        private static void writeDeepCollections(DependencyObject target, XmlWriter writer)
        {
            PropertyInfo[] props = target.GetType().GetProperties();
            object val;
            foreach (var prop in props)
                if (prop.PropertyType.BaseType.Name != "Collection`1" && prop.PropertyType.Name != "Transform" && XamlHelper.hasDeepCollections(target, prop))
                {
                    val = prop.GetValue(target, null);
                    if (val != null & val.GetType().Equals(typeof(DependencyObject)))
                    {
                        writer.WriteStartElement(prop.Name);
                        writeCollections((DependencyObject)val, writer);
                        writer.WriteEndElement();
                    }
                }
        }
    }
}

 

示例:

 

前台代码:

<Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="200"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Canvas Height="100" Width="200" x:Name="myCanvas" Background="Beige">
            <TextBlock Text="Amyo Kabir"></TextBlock>
        </Canvas>
        <TextBox Grid.Row="1" x:Name="textBoxOutput"></TextBox>
    </Grid>

  

后台代码:

var root = XamlWriter.Write(myCanvas).Replace("x:", "");
            var elm = XElement.Parse(root);
            foreach (var child in myCanvas.Children)
            {
                elm.Add(XElement.Parse(XamlWriter.Write(child).Replace("x:", "")));
            }
            textBoxOutput.Text = elm.ToString();

 

 

textBoxOutput的内容为:

 

<Canvas Width="200" Height="100" MinWidth="0" MinHeight="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0" FlowDirection="LeftToRight" Name="myCanvas" AllowDrop="False" Opacity="1" RenderTransformOrigin="0,0" IsHitTestVisible="True" Visibility="Visible" UseLayoutRounding="True" Canvas.Left="0" Canvas.Top="0" Canvas.ZIndex="0">
  <Canvas.Background>
    <SolidColorBrush Color="#FFF5F5DC" Opacity="1" />
  </Canvas.Background>
  <TextBlock FontSize="11" FontFamily="Portable User Interface" FontWeight="Normal" FontStyle="Normal" FontStretch="Normal" TextWrapping="NoWrap" TextTrimming="None" TextAlignment="Left" Text="Amyo Kabir" Padding="0,0,0,0" LineHeight="0" LineStackingStrategy="MaxHeight" MinWidth="0" MinHeight="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0" FlowDirection="LeftToRight" AllowDrop="False" Opacity="1" RenderTransformOrigin="0,0" IsHitTestVisible="True" Visibility="Visible" UseLayoutRounding="True" Canvas.Left="0" Canvas.Top="0" Canvas.ZIndex="0">
    <TextBlock.Foreground>
      <SolidColorBrush Color="#FF000000" Opacity="1" />
    </TextBlock.Foreground>
  </TextBlock>
</Canvas>

 

分享到:
评论

相关推荐

    基于opencv实现象棋识别及棋谱定位python源码+数据集-人工智能课程设计

    基于opencv实现象棋识别及棋谱定位python源码+数据集-人工智能课程设计,含有代码注释,满分课程设计资源,新手也可看懂,期末大作业、课程设计、高分必看,下载下来,简单部署,就可以使用。该项目可以作为课程设计期末大作业使用,该系统功能完善、界面美观、操作简单、功能齐全、管理便捷,具有很高的实际应用价值。 基于opencv实现象棋识别及棋谱定位python源码+数据集-人工智能课程设计,含有代码注释,满分课程设计资源,新手也可看懂,期末大作业、课程设计、高分必看,下载下来,简单部署,就可以使用。该项目可以作为课程设计期末大作业使用,该系统功能完善、界面美观、操作简单、功能齐全、管理便捷,具有很高的实际应用价值。 基于opencv实现象棋识别及棋谱定位python源码+数据集-人工智能课程设计,含有代码注释,满分课程设计资源,新手也可看懂,期末大作业、课程设计、高分必看,下载下来,简单部署,就可以使用。该项目可以作为课程设计期末大作业使用,该系统功能完善、界面美观、操作简单、功能齐全、管理便捷,具有很高的实际应用价值。基于opencv实现象棋识别及棋谱定位python源码+数据集

    基于Python实现的Cowrie蜜罐设计源码

    该项目为基于Python实现的Cowrie蜜罐设计源码,共计380个文件,涵盖166个Python源代码文件,以及包括RST、SQL、YAML、Markdown等多种类型的配置和文档文件。Cowrie蜜罐是一款用于记录暴力攻击和攻击者执行的SSH及Telnet交互的中等交互式蜜罐。

    QT 摄像头获取每一帧图像数据以及opencv获取清晰度

    QT 摄像头获取每一帧图像数据以及opencv获取清晰度

    基于asp.net的(CS)地震预测系统设计与实现.docx

    基于asp.net的(CS)地震预测系统设计与实现.docx

    基于Springboot和Mysql的医院药品管理系统代码(程序,中文注释)

    医院药品管理系统-医院药品管理系统-医院药品管理系统-医院药品管理系统-医院药品管理系统-医院药品管理系统-医院药品管理系统-医院药品管理系统-医院药品管理系统-医院药品管理系统-医院药品管理系统-医院药品管理系统 1、资源说明:医院药品管理系统源码,本资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 2、适用人群:计算机相关专业(如计算计、信息安全、大数据、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工等学习者,作为参考资料,进行参考学习使用。 3、资源用途:本资源具有较高的学习借鉴价值,可以作为“参考资料”,注意不是“定制需求”,代码只能作为学习参考,不能完全复制照搬。需要有一定的基础,能够看懂代码,能够自行调试代码,能够自行添加功能修改代码。 4. 最新计算机软件毕业设计选题大全(文章底部有博主联系方式): https://blog.csdn.net/2301_79206800/article/details/135931154 技术栈、环境、工具、软件: ① 系统环境:Windows ② 开发语言:Java ③ 框架:SpringBo

    mqtt单点到点聊天工具

    mqtt单点到点聊天工具

    【图像融合】基于matlab GUI拉普拉斯金字塔+小波变换图像融合【含Matlab源码 857期】.zip

    CSDN海神之光上传的代码均可运行,亲测可用,直接替换数据即可,适合小白; 1、代码压缩包内容 主函数:main.m; 调用函数:其他m文件;无需运行 运行结果效果图; 2、代码运行版本 Matlab 2019b;若运行有误,根据提示修改;若不会,私信博主; 3、运行操作步骤 步骤一:将所有文件放到Matlab的当前文件夹中; 步骤二:双击打开main.m文件; 步骤三:点击运行,等程序运行完得到结果; 4、仿真咨询 如需其他服务,可私信博主或扫描博客文章底部QQ名片; 4.1 博客或资源的完整代码提供 4.2 期刊或参考文献复现 4.3 Matlab程序定制 4.4 科研合作 图像融合:小波变换图像融合、遗传算法图像融合、IHS图像融合、PCA图像融合、curvelet变换图像融合、拉普拉斯金字塔+NSCT图像融合、医学图像图像融合、高分辨全色图像融合 DSIFT多聚焦图像融合、加权平均法图像融合、泊松彩色图像融合、主成分结合小波离散变换PCA-DWT图像融合、矩阵优化图像融合、导向滤波图像融合、拉普拉斯图像融合、系数绝对值最大图像融合

    基于ZCAM E2系列相机的OBS设计源码实现

    该项目为OBS直播软件的扩展设计源码,采用C++语言编写,并包含C、Shell和C等其他语言。源码共99个文件,其中包含16个头文件、11个PowerShell脚本、9个C++源文件、6个ZSH脚本、5个Shell脚本、5个输入文件、4个INI配置文件、3个YAML文件、3个文本文件、2个JSON文件。源码实现将ZCAM E2系列相机直接集成至OBS作为直播源,支持直播功能。

    VLOOKUP函数:在Excel中查找并返回数组特定元素的实用指南

    在Excel中处理数据时,我们经常需要从大量数据中提取特定的信息。VLOOKUP函数(垂直查找函数)是一个非常强大的工具,它可以帮助我们在数据表中查找并返回相应的值。本文将详细探讨如何使用VLOOKUP函数查找并返回数组中的特定元素,包括函数的语法、使用技巧和实际应用中的代码示例。 VLOOKUP函数是Excel中进行数据查找和提取的强大工具。通过使用VLOOKUP进行精确匹配、近似匹配、数组公式和反向查找,可以有效地从数组中查找并返回特定的元素。此外,使用IFERROR和数据类型检查可以提高数据查找的准确性和可靠性。通过这些技巧和方法,可以确保VLOOKUP函数在各种情况下都能准确无误地执行。

    拷贝到Windows 10的C:\Windows\System32或C:\Windows\SysWOW64,之后重启电脑

    拷贝到Windows 10的C:\Windows\System32或C:\Windows\SysWOW64,之后重启电脑

    excel统计分析(3): 一元线性回归分析

    excel统计分析(3): 一元线性回归分析

    基于matlab碳交易机制下考虑需求响应的优化运行【含Matlab源码 期】.zip

    CSDN海神之光上传的全部代码均可运行,亲测可用,直接替换数据即可,适合小白; 1、代码压缩包内容 主函数:main.m; 调用函数:其他m文件;无需运行 运行结果效果图; 2、代码运行版本 Matlab 2019b;若运行有误,根据提示修改;若不会,可私信博主; 3、运行操作步骤 步骤一:将所有文件放到Matlab的当前文件夹中; 步骤二:双击打开main.m文件; 步骤三:点击运行,等程序运行完得到结果; 4、仿真咨询 如需其他服务,可私信博主或扫描博主博客文章底部QQ名片; 4.1 CSDN博客或资源的完整代码提供 4.2 期刊或参考文献复现 4.3 Matlab程序定制 4.4 科研合作

    精简博客系统 基于Springboot和Mysql的精简博客系统代码(程序,中文注释)

    精简博客系统-精简博客系统-精简博客系统-精简博客系统-精简博客系统-精简博客系统-精简博客系统-精简博客系统-精简博客系统-精简博客系统-精简博客系统-精简博客系统 1、资源说明:精简博客系统源码,本资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 2、适用人群:计算机相关专业(如计算计、信息安全、大数据、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工等学习者,作为参考资料,进行参考学习使用。 3、资源用途:本资源具有较高的学习借鉴价值,可以作为“参考资料”,注意不是“定制需求”,代码只能作为学习参考,不能完全复制照搬。需要有一定的基础,能够看懂代码,能够自行调试代码,能够自行添加功能修改代码。 4. 最新计算机软件毕业设计选题大全(文章底部有博主联系方式): https://blog.csdn.net/2301_79206800/article/details/135931154 技术栈、环境、工具、软件: ① 系统环境:Windows ② 开发语言:Java ③ 框架:SpringBoot ④ 架构:B/S、MVC ⑤ 开发环境:IDE

    基于Scrapy框架的豆瓣电影爬虫系统

    项目介绍使用Scrapy框架爬取豆瓣电影,豆瓣选影视页面分别筛选地区为中国大陆、香港、台湾(可更换为其他地区),构造Ajax请求,获取电影id,再通过id构造电影链接,解析页面后获得电影详细数据,如名称、年份、导演、主演、类型等。 在IT行业中,网络爬虫是获取大量数据的重要手段,尤其在金融数据分析领域,如股票评论数据,能够为投资者提供宝贵的市场情绪参考。本项目聚焦于使用Python的Scrapy框架来批量爬取豆瓣电影网的数据,从而进行数据分析。 Scrapy是一个强大的Python爬虫框架,它提供了一整套解决方案,包括网页抓取、解析、数据存储等。使用Scrapy,我们可以高效地构建起一个完整的爬虫项目,其主要组件包括Spiders、Item、Item Pipeline、Downloader Middleware和Settings等。 1. **Spiders**:是Scrapy的核心,负责定义如何抓取数据以及如何处理抓取到的数据。在这个项目中,我们需要创建一个Spider,设置其起始URL(通常是豆瓣电影网的评论页面),并定义如何解析HTML页面,提取评论内容、用户名、

    基于c语言的配有图片和音乐的打字母游戏.zip

    基于c语言的配有图片和音乐的打字母游戏.zip

    基于asp.net的歌迷购物网设计与实现.docx

    基于asp.net的歌迷购物网设计与实现.docx

    基于Vue框架的hao123程序员网址导航设计源码

    该项目是一款基于Vue框架构建的程序员网址导航系统源码,包含136个文件,包括56个PNG图片、49个ICO图标、11个Vue组件文件、5个JavaScript文件以及少量JSON、YAML和其他配置文件。该系统以简洁明了的界面,为程序员提供便捷的网址导航服务。

    MPU6050 DMP文件移植包

    MPU6050 DMP文件移植包

    PyOpenGL-3.0.1 (2).zip

    opengl安装包

    螺旋轴泵3D模型图纸 Solidworks设计 附STEP格式.zip

    螺旋轴泵3D模型图纸 Solidworks设计 附STEP格式.zip

Global site tag (gtag.js) - Google Analytics