0

我们有一些翻译标记扩展,如下所示:

TextBlock Text="{l:Translate 'My string'}"

我们希望(因为我们可以使用其他一些工具进行 xaml 翻译)自动替换所有项目 xaml 中的文本标签。

有没有办法用正则表达式或 xml 读取器/写入器找出所有节点或属性来实现这种情况?

4

2 回答 2

0

我们使用了正则表达式,这不是最好的方法,但我们可以放弃它。

于 2013-07-16T08:38:27.450 回答
0

本质上,XAML符合标准XML,但要使用它,您需要外部库。例如:(Microsoft XAML Toolkit CTP下载。简单示例,显示项目列表:

// Previously adding the library
using Microsoft.Xaml.Tools.XamlDom;

XamlDomObject rootObject = XamlDomServices.Load("MainWindow.xaml");

foreach (XamlDomObject domObject in rootObject.DescendantsAndSelf())
{
    MessageBox.Show(domObject.Type.ToString());
}

在文档中设置Background每个:Control

XamlDomObject rootObject = XamlDomServices.Load("MainWindow.xaml");
    foreach (XamlDomObject objectNode in
        from control in rootObject.DescendantsAndSelf(typeof(Control))
        where !control.HasMember("Background")
        select control)
{
    objectNode.SetMemberValue("Background", "Red");
}

XamlDomServices.Save(rootObject, "NewFile.xaml");

对于替换Text属性值,我使用示例:

private void Window_ContentRendered(object sender, EventArgs e)
{
    XamlDomObject rootObject = XamlDomServices.Load("MainWindow.xaml");

    foreach (XamlDomObject objectNode in
            from control in rootObject.DescendantsAndSelf(typeof(TextBlock))
            where control.HasMember("Text")
            select control)
    {
            objectNode.SetMemberValue("Text", "MyInsertedText");
    }

    XamlDomServices.Save(rootObject, "NewFile.xaml");
} 

文件Input

<Window x:Class="XAMLdom.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" ContentRendered="Window_ContentRendered">

    <Grid>
        <TextBlock Text="SomeText" Width="100" Height="30" />
    </Grid>
</Window>

文件Output

<?xml version="1.0" encoding="utf-8"?>
<Window xml:base="file:///C:/Documents and Settings/Kanc/мои документы/visual studio 2010/Projects/XAMLdom/XAMLdom/bin/Debug/MainWindow.xaml" x:Class="XAMLdom.MainWindow" Title="MainWindow" Height="350" Width="525" ContentRendered="Window_ContentRendered" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <TextBlock Text="MyInsertedText" Width="100" Height="30" />
    </Grid>
</Window>
于 2013-07-05T04:44:29.357 回答