【问题标题】:Extracting Propreties to Styles (Xaml processing tool)将属性提取到样式(Xaml 处理工具)
【发布时间】:2011-12-11 00:21:30
【问题描述】:

我需要将控件的道具(高度、宽度、水平对齐等)提取到样式中。

你们知道有什么工具可以做到这一点吗?

我已经尝试过 Xaml Power 工具(很好,但只处理 xml 之类的属性属性,例如:无法识别) 还查看了表情混合..也没有找到任何东西。

至少有一些框架/api可以轻松解析xaml(找到了Xaml Toolkit,但它在2010年仍然是CTP版本..)

谢谢!

【问题讨论】:

  • 问题。解析 Xaml 只会为您提供已在本地设置的样式属性。由其他方法设置的属性,例如 WPF 强制、绑定、对象图中已经存在的资源字典,甚至从模板化父级派生的属性都将丢失。那么您是否希望仅捕获已在本地和以声明方式设置的那些属性?或者,您是否想在元素构建后捕捉其视觉外观?
  • 你觉得下面贴的答案合适吗?

标签: wpf xaml styles


【解决方案1】:

如果您已经创建了一个元素并指定了属性,例如下面的 Slider 控件。

<Window x:Class="Styling.ExtractStyle"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ViewTemplateSource" Height="300" Width="300">
    <Window.Resources>
    </Window.Resources>
    <Grid Name="g1">
        <Slider Name="mySlider" Height="100" VerticalAlignment="Center">
            <Slider.Width>200</Slider.Width>
        </Slider>        
    </Grid>
</Window> 

您可以实现对 FrameworkElement 类的扩展...

public static class FrameworkElementExtensions
{
    public static void SaveElementStyleToFile(this FrameworkElement element, string fileName)
    {
        if (element != null)
        {
            XmlWriterSettings settings = new XmlWriterSettings
            {
                Indent = true,
                IndentChars = new string(' ', 4),
                NewLineOnAttributes = true
            };
            StringBuilder strbuild = new StringBuilder();
            XmlWriter xmlwrite = XmlWriter.Create(strbuild, settings);
            if (xmlwrite != null)
            {
                XamlWriter.Save(element, xmlwrite);
            }
            File.WriteAllText(fileName, strbuild.ToString());
        }
        else
        {
            throw new Exception("Cannot serialize a null object");
        }
    }
}

并调用扩展方法...

mySlider.SaveElementStyleToFile("mySliderStyle.xaml");

这将在应用程序的根目录中为您提供一个 XML 文件,该文件捕获“硬编码”属性。这是它的输出...

<?xml version="1.0" encoding="utf-16"?>
<Slider
    Name="mySlider"
    Width="200"
    Height="100"
    VerticalAlignment="Center" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" />

然后,您可以使用编辑器将此文件变形为持久样式。请注意,必须首先通过 WPF 的两遍布局系统运行目标框架元素才能使该技术发挥作用。

例如

文本框 t = new TextBox(); t.高度 = 20; t.SaveElementStyleToFile("myfile.xml");

出于这个原因工作。缺少 Xaml Power Toys 和/或完整的 Xaml 解析器提供的便利,这可能会尽可能满足您的要求...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 2021-07-09
    相关资源
    最近更新 更多