动态添加的控件未显示在WPF页面中

时间:2020-09-14 08:15:57

标签: c# wpf xaml revit-api

我试图使用WPF构建Revit插件,并且试图向窗口动态添加控件。但是,这些控件不会显示在窗口中,并且没有错误。任何帮助,将不胜感激。谢谢。

Xaml

    <ScrollViewer Margin="0,190,-0.4,-1">
        <StackPanel Name="TaskList" Height="auto" Width="auto">
        </StackPanel>
    </ScrollViewer>

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();
    }

编辑 我正在使用页面标签作为基本窗口。也许这改变了我应对问题的方式?

2 个答案:

答案 0 :(得分:0)

完全删除Canvas。您可以将TextBox元素直接添加到StackPanelTaskList)中。如果需要边框或间距,则应使用Border控件,而不要使用Canvas

此外,仅在您将所有控件添加到其后的 后调用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();

答案 1 :(得分:0)

考虑使用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>

然后仅将字符串添加到其Items属性:

for (var i = 0; i < dt.Rows.Count; i++)
{
    TaskList.Items.Add(dt.Rows[i][2].ToString());
}
相关问题