使用xml文件向网格添加控件

时间:2012-03-24 18:16:39

标签: c# wpf wpf-controls

此代码将任何控件或对象转换为xml


如果我保存了这个screenshot


保存的xml看起来像:

<Grid Name="g" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Image Source="pack://application:,,,/WpfApplication1;component/Images/Picture3.jpg" Stretch="Fill" Name="image1" Width="200" Height="150" Margin="96,36,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" />
<Button Name="button1" Width="75" Height="23" Margin="352,71,0,0" HorizontalAlignment="Left" VerticalAlignment="Top">Button</Button>
<TextBox Name="textBox1" Width="120" Height="23" Margin="62,198,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" xml:space="preserve" />
<Label Name="label1" Height="28" Margin="270,213,0,0" HorizontalAlignment="Left" VerticalAlignment="Top">Label</Label>
</Grid>


我用这段代码保存了这个:

 System.IO.StreamWriter s = new System.IO.StreamWriter(@"d:\grid.xml");
            s.WriteLine(System.Windows.Markup.XamlWriter.Save(g));
            s.Close();

g是包含所有控件的网格名称

我的问题:
我可以撤消这个,读取这个xml文件并在窗口上表示它

2 个答案:

答案 0 :(得分:1)

只需使用XAML Reader类。

答案 1 :(得分:0)

var somecontrol = XamlReader.Load(@"<ItemsPanelTemplate
                xmlns=""http://schemas.microsoft.com/client/2007"" 
                xmlns:toolkit=""http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"">
                <toolkit:WrapPanel /></ItemsPanelTemplate>");