简体   繁体   English

无法通过 XamlReader 加载 XAML

[英]Unable to load XAML through XamlReader

I have a WPF application.我有一个 WPF 应用程序。 Source is here .来源在这里 My requirement is, if the use click the Save button, I want to capture the current window's XAML including inputs and save it to the database.我的要求是,如果用户单击“保存”按钮,我想捕获当前窗口的 XAML(包括输入)并将其保存到数据库中。 After that in application, somewhere else, I need to load back that window from DB.在应用程序中,在其他地方之后,我需要从数据库加载该窗口。 I tried this using XamlWriter .我使用XamlWriter尝试了这个。 Its working fine if I didnt name the controls in Xaml.如果我没有在 Xaml 中命名控件,它工作正常。 If I add x:Name attribute in Xaml for any control, it gives exception as shown below.如果我在 Xaml 中为任何控件添加 x:Name 属性,它会给出如下所示的异常。 Please help.请帮忙。

在此处输入图片说明

if you put a Console.WriteLine(window);如果你放一个Console.WriteLine(window); behind var window = XamlWriter.Save(this);后面var window = XamlWriter.Save(this); like so:像这样:

 var window = XamlWriter.Save(this);
 Console.WriteLine(window);

you get this printed:你得到这个打印:

<MainWindow Title="MainWindow" Width="525" Height="350" Visibility="Visible" xmlns="clr-namespace:XamlReaderSample;assembly=XamlReaderSample" xmlns:av="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><av:Grid><av:StackPanel Margin="0,10,0,0">
<av:TextBox Width="100" xml:space="preserve" /><av:TextBox Width="100" Margin="0,10,0,0" xml:space="preserve" />
<av:Button Name="btnSave" Width="80" Margin="0,10,0,0">Save</av:Button> 
</av:StackPanel></av:Grid></MainWindow>

within this code there is a button named btnSave.在这段代码中有一个名为 btnSave 的按钮。 in the rest of your code you try to create a new window from that code.在您的其余代码中,您尝试从该代码创建一个新窗口。 once you try to create that window, you have a 2nd button (besides the one you did click) with that name.一旦您尝试创建该窗口,您就会有一个具有该名称的第二个按钮(除了您单击的那个)。 and that causes the error.这会导致错误。

I tried like this and it worked.我像这样试过,它奏效了。

var win = new Window();
win.Name = this.Name;
win.Content = this.Content;
var xaml = XamlWriter.Save(win);

But still I cant do like this if the window have a DataGrid in it, since DataGrid doesnt support serialization.但是如果窗口中有 DataGrid,我仍然不能这样做,因为 DataGrid 不支持序列化。 Need to find out some other method.需要寻找其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM