如何将数据绑定XAML控件呈现给本机XAML绘图

时间:2011-02-10 14:26:17

标签: c# wpf xaml data-binding binding

我有一个数据绑定的XAML控件,如下所示:

<UserControl>
    <TextBlock Text="{Binding Text}" />
</UserControl>

并希望它像这样呈现为'绘图':

<UserControl>
    <TextBlock Text="Actual text value" />
</UserControl>

有谁知道如何从任意控件中提取图形?

更新: 这个问题似乎并不清楚。所以我试着解释一下。 输入是带数据绑定的XAML控件。现在我想将它转换为普通的XAML而不需要任何数据绑定。输出可以写入磁盘并由任何理解XAML的应用程序显示,而不会绑定任何内容。

所以解决方案应该是这样的:

FrameworkElementinput = (FrameworkElement)XamlReader.Read(inputFile);
input.DataContext = dataObject;
FrameworkElement output = ConvertToNative(input);
XamlWriter.Write(outputFile, output);

我正在寻找'ConvertToNative'

的实现

1 个答案:

答案 0 :(得分:2)

如果您要为UserControl执行此操作,请务必先删除x:Class属性,否则将获得XamlParseException

您可以使用XamlReader.Load加载Xaml文件,当您使用XamlWriter.Save保存时,绑定会转换为实际值。将Bindings更新似乎有些麻烦,所以我通过订阅Loaded事件并将其添加到UI中的容器,并在事件处理程序中从容器中删除if然后保存它来解决这个问题。这可能会以更好的方式解决..

private void SomeMethod()
{
    CreateXamlWithBindingValues("UserControl1.xaml", "UserControl1_Saved.xaml");
}
private void CreateXamlWithBindingValues(string sourcePath, string savePath)
{
    StreamReader streamReader = new StreamReader(sourcePath);
    StringReader stringReader = new StringReader(streamReader.ReadToEnd());
    XmlReader xmlReader = XmlReader.Create(stringReader);
    FrameworkElement loadedObject = (FrameworkElement)XamlReader.Load(xmlReader);
    loadedObject.DataContext = UserControlViewModel;

    RoutedEventHandler routedEventHandler = null;
    routedEventHandler = new RoutedEventHandler(delegate
    {
        loadedObject.Loaded -= routedEventHandler;
        grid1.Children.Remove(loadedObject);

        string savedObject = XamlWriter.Save(loadedObject);
        StreamWriter streamWriter = new StreamWriter(savePath);
        streamWriter.Write(savedObject);
        streamWriter.Close();
    });
    loadedObject.Loaded += routedEventHandler;
    grid1.Children.Add(loadedObject);
}

保存前的Xaml

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBlock Text="{Binding Text}"/>
    </Grid>
</UserControl>

保存后的Xaml 如您所见,没有换行符,但Text值是绑定产生的值

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><Grid><TextBlock Text="Actual Text Value" /></Grid></UserControl>

保存前的Xaml

<Grid Name="grid1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Button Content="{Binding MyContent}"/>
</Grid>

保存后的Xaml

<Grid Name="grid1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><Button>Actual Content</Button></Grid>