`
jiasongmao
  • 浏览: 682732 次
  • 性别: 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>

 

分享到:
评论

相关推荐

    XamlReader Demo

    XamlReader是.NET框架中用于解析XAML(Extensible Application Markup Language)文档的工具,它允许程序在运行时动态加载和解析XAML资源,将其转换为对象实例。在Silverlight开发中,XamlReader起到了关键作用,...

    Silverlight 入门

    createFromXaml方法用于动态解析XAML字符串并创建对象,这在运行时创建和修改UI非常有用。访问和修改元素及属性通常通过FindName方法和依赖属性(Dependency Property)机制来实现。 五、图形与画刷 Silverlight...

    windows编程,设计6

    离散式对象值动画用于处理非数值类型的属性,如字符串。 **8.4.5 相关主题** - [关键帧动画概览](https://docs.microsoft.com/zh-cn/windows/uwp/controls-and-patterns/keyframe-animations-overview) - [缓动函数...

    支持pyramid2.x的kotti web代码

    Kotti 是一个基于 Pyramid 框架的 Python 内容管理系统(CMS),适合用来搭建中小型网站、文档库、企业展示平台、知识库等需要灵活内容结构和权限模型的项目。它本身更像一个可以二次开发的 CMS 框架,比 WordPress、Drupal 这类“一装就用”的系统更倾向于开发者定制和扩展。 这是支持pyramid2.x版本的kotti! tar -xzvf kotti1.0.tar.gz 解压缩 进入目录执行 pip install -e . 来安装, 然后执行pserve app.ini 启动。 用浏览器浏览127.0.0.1:5000 即可浏览。 用户名admin ,口令qwerty

    cmd-bat-批处理-脚本-hello world.zip

    cmd-bat-批处理-脚本-hello world.zip

    知识付费系统自动采集V3.0 跳转不卡顿+搭建教程

    知识付费系统自动采集V3.0 跳转不卡顿+搭建教程,不和外面的一样跳转卡顿,这个跳转不卡顿,支持三级分销。

    基于Matlab实现图像形状纹理颜色特征提取

    在Matlab环境下,对图像进行特征提取时,主要涵盖形状、纹理以及颜色这三大关键特征。其中,对于纹理特征的提取,采用灰度梯度共生矩阵这一方法来实现。通过灰度梯度共生矩阵,可以有效地捕捉图像中像素灰度值之间在不同方向和距离上的相互关系,进而量化地反映出图像的纹理特性,为后续的图像分析、分类等任务提供重要的纹理信息依据。

    实证数据-2010-2023年上市公司-管理层情感语调数据-社科经管.rar

    该数据集为2010-2023年中国A股上市公司管理层情感语调的年度面板数据,覆盖45,320条样本,数据源自年报及半年报的"管理层讨论与分析"部分。通过构建中文金融情感词典(融合《知网情感分析用词典》与L&M金融词汇表),采用文本分析方法计算情感语调指标,包括:正面/负面词汇数量、文本相似度、情感语调1((积极词-消极词)/总词数)和情感语调2((积极词-消极词)/(积极词+消极词))。同时包含盈利预测偏差、审计意见类型等衍生指标,可用于研究信息披露质量、市场反应及代理问题。该数据复刻了《管理世界》《财经研究》等期刊的变量构建方法,被应用于分析语调操纵对债券市场的影响,学术常用度与稀缺度较高。

    cmd-bat-批处理-脚本-FTIME.zip

    cmd-bat-批处理-脚本-FTIME.zip

    1747829038637.png

    1747829038637.png

    2025年自动化X光检查机项目大数据研究报告.docx

    2025年自动化X光检查机项目大数据研究报告.docx

    基于Logisim的原码与补码一位乘法器设计

    在计算机组成原理课程设计中,我全程跟随老师的指导,独立完成了以下两项任务:一是利用Logisim软件进行原码一位乘法器的仿真设计,通过逐步搭建电路、配置逻辑单元,实现了原码乘法运算的完整流程,深入理解了原码乘法的原理和实现机制;二是完成了补码一位乘法器的Logisim仿真,同样按照老师讲解的步骤,精心设计电路,确保补码乘法运算的正确性,进一步掌握了补码乘法的运算规则和电路实现方法。通过这两个项目,我不仅巩固了理论知识,还提升了动手实践能力和逻辑思维能力。

    cmd-bat-批处理-脚本-msvc2017.zip

    cmd-bat-批处理-脚本-msvc2017.zip

    cmd-bat-批处理-脚本-virtualcam-install.zip

    cmd-bat-批处理-脚本-virtualcam-install.zip

    二十四节气之立秋介绍.pptx

    二十四节气之立秋介绍.pptx

    cmd-bat-批处理-脚本-shift.zip

    cmd-bat-批处理-脚本-shift.zip

    二十四节气之小雪介绍.pptx

    二十四节气之小雪介绍.pptx

    java、SpringBoot面试专题,6页面试题

    java、SpringBoot面试专题,6页面试题

    cmd-bat-批处理-脚本-GenerateUnionWinMD.zip

    cmd-bat-批处理-脚本-GenerateUnionWinMD.zip

    二十四节气之大暑节气.pptx

    二十四节气之大暑节气.pptx

Global site tag (gtag.js) - Google Analytics