如何在运行时从其 XAML 字符串添加 WPF 网格控件?
假设我们有一个如下所示的网格 XAML - 例如。从方法返回的生成字符串。
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width='*' />
<ColumnDefinition Width='*' />
</Grid.ColumnDefinitions>
<TextBlock Text='id' Grid.Column='0'/>
<Rectangle Fill='Black' Grid.Column='1' />
</Grid>
我想要做的是创建这样一个网格并在运行时添加到堆栈面板中,代码类似于下面。
XmlReader xr = XmlReader.Create(input: new StringReader(g.xaml));
var control = XamlReader.Load(xr) as Grid;
this.stackPanel.Children.Add(control);
我使用的形式是:
<Window x:Class='AllRibbonBrushes.MainWindow'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
Title='MainWindow' Height='223' Width='533'
Loaded='Window_Loaded'>
<ScrollViewer>
<StackPanel Name="stackPanel">
<!--The runtime grid need to be added here-->
</StackPanel>
</ScrollViewer>
</Window>
但我收到错误无法创建未知类型'Grid'
。我通过添加按钮/文本块成功做到了这一点,但未能添加带有嵌套控件的网格。
如果您知道如何操作,请分享。欢迎并非常感谢所有帮助!
Let's say we have a grid XAML like below - eg. a generated string returned from a method.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width='*' />
<ColumnDefinition Width='*' />
</Grid.ColumnDefinitions>
<TextBlock Text='id' Grid.Column='0'/>
<Rectangle Fill='Black' Grid.Column='1' />
</Grid>
What I want to do is to create such a grid and added to a stackpanel at run time, codes similar as below.
XmlReader xr = XmlReader.Create(input: new StringReader(g.xaml));
var control = XamlReader.Load(xr) as Grid;
this.stackPanel.Children.Add(control);
The form I use is:
<Window x:Class='AllRibbonBrushes.MainWindow'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
Title='MainWindow' Height='223' Width='533'
Loaded='Window_Loaded'>
<ScrollViewer>
<StackPanel Name="stackPanel">
<!--The runtime grid need to be added here-->
</StackPanel>
</ScrollViewer>
</Window>
But I get the error Cannot create unknow type 'Grid'
. I succeed doing this by adding a button/a textblock but failed to add a grid with nested controls.
If you know how to do so, please share. All helps are welcome and very much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
添加到要加载的 xaml 中的第一个 Grid 元素。这将 wpf 命名空间声明为 xaml 中的默认命名空间。然后 XamlReader.Load 可以找出控件是什么类型。Add
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
to the first Grid element in the xaml you would like load. This declares the wpf namespace the default namespace in your xaml. XamlReader.Load can then find out what kind of control is.