我们有一些翻译标记扩展名,如下所示:
TextBlock Text="{l:Translate 'My string'}"
我们希望(因为我们可以使用其他一些工具进行xaml转换)自动替换所有项目xamls中的文本标签。
有没有办法找到所有带有正则表达式或xml reader / write的节点或属性来实现这种情况?
答案 0 :(得分:0)
基本上,XAML
符合标准XML
,但要使用它,您需要外部库。例如:Microsoft XAML Toolkit CTP
(download)。简单示例,显示项目列表:
// 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>
答案 1 :(得分:0)
我们使用的是正则表达式,这不是最好的方法,但我们可以随身携带。