[英]Dynamically added controls not displaying in wpf page
I am trying to build a Revit plugin using WPF and I am trying to add controls to a window dynamically.我正在尝试使用 WPF 构建一个 Revit 插件,并且我正在尝试动态地向窗口添加控件。 However, these controls are not getting displayed in the window and there is no error.
但是,这些控件没有显示在窗口中,并且没有错误。 Any help would be appreciated.
任何帮助,将不胜感激。 Thank you.
谢谢你。
Xaml xml
<ScrollViewer Margin="0,190,-0.4,-1">
<StackPanel Name="TaskList" Height="auto" Width="auto">
</StackPanel>
</ScrollViewer>
c# C#
for (var i = 0; i < dt.Rows.Count; i++)
{
Canvas canvas = new Canvas();
canvas.Height = 100;
canvas.Width = 300;
canvas.Background = new SolidColorBrush(Colors.Black);
canvas.Margin = new Thickness(20);
System.Windows.Controls.TextBox tb = new System.Windows.Controls.TextBox();
tb.Background = new SolidColorBrush(Colors.Black);
tb.Foreground = new SolidColorBrush(Colors.White);
tb.Width = 300;
tb.FontSize = 30;
tb.Height = 100;
tb.TextWrapping = TextWrapping.Wrap;
tb.MaxLength = 40;
tb.Text = dt.Rows[i][2].ToString();
canvas.Children.Add(tb);
TaskList.Children.Add(canvas);
TaskList.UpdateLayout();
}
EDIT I am using a page tag as the base not window.编辑我使用页面标签作为基础而不是窗口。 Maybe that changes how i should approach the problem?
也许这会改变我应该如何解决这个问题?
Remove Canvas
entirely.完全删除
Canvas
。 You can add the TextBox
elements to the StackPanel
( TaskList
) directly.您可以直接将
TextBox
元素添加到StackPanel
( TaskList
)。 If you want a border or spacing then you should use the Border
control, not Canvas
.如果您想要边框或间距,则应使用
Border
控件,而不是Canvas
。
Additionally, only call UpdateLayout()
after you've added all the controls to it:此外,只有调用
UpdateLayout()
添加完所有的控件之后:
using System.Windows.Controls;
...
for (var i = 0; i < dt.Rows.Count; i++)
{
TextBox tb = new TextBox();
tb.Background = new SolidColorBrush( Colors.Black );
tb.Foreground = new SolidColorBrush( Colors.White );
tb.Width = 300;
tb.FontSize = 30;
tb.Height = 100;
tb.TextWrapping = TextWrapping.Wrap;
tb.MaxLength = 40;
tb.Text = dt.Rows[i][2].ToString();
this.TaskList.Children.Add( tb );
}
this.TaskList.UpdateLayout();
Consider using an ItemsControl, instead of creating UI elements in code behind:考虑使用 ItemsControl,而不是在后面的代码中创建 UI 元素:
<ScrollViewer>
<ItemsControl x:Name="TaskList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Width="300" Height="100" FontSize="30"
TextWrapping="Wrap" Text="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
Then just add strings to its Items property:然后只需将字符串添加到其 Items 属性:
for (var i = 0; i < dt.Rows.Count; i++)
{
TaskList.Items.Add(dt.Rows[i][2].ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.