How to replace Xaml Text with Text based on MarkUp extensions automatically

advertisements

We have some translation mark up extension which looks like this:

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

and we want (because we could use some other tool for xaml translation) to replace text tags inside of all project xamls automatically.

Is there any way to find out all nodes or attributes with regex or with xml reader/write to implement this case?


Essentially, XAML meets the standard XML, but to work with it, you need external libraries. As an example: Microsoft XAML Toolkit CTP (download). Simple example, which displays a list of items:

// 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());
}

Set Background on every Control in your document:

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");

For replace value of Text property, I use example:

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");
}

File 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>

File 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>