如何将新创建的控件附加到 C# 中的另一个控件 [英] How can I append a newly created control to another control in c#

查看:29
本文介绍了如何将新创建的控件附加到 C# 中的另一个控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然是 VS、C# 和 XAML 的新手.我有这个 XAML 代码

I am still a newbie to VS, C# and XAML. I have this XAML code

<ListBox Background="Black" x:Name="ListBox1" Width="900" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal" Width="{Binding ElementName=ListBox1, Path=Width}"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

现在我想使用 c# 创建另一个子控件并将其添加到 ListBox 控件.我使用下面的这段代码来创建一个 ListBoxItem 控件

Now I want to create and add another child control to the ListBox control using c#. I use this code below to create a ListBoxItem control

ListBoxItem li = new ListBoxItem();
li.Background = Brushes.White;
li.Width = 150;
li.Height = 200;
Thickness margin = li.Margin;
margin.Left = 5;
margin.Right = 5;
margin.Top = 5;
margin.Bottom = 5;
li.Margin = margin;
li.VerticalAlignment = System.Windows.VerticalAlignment.Top;
li.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;

然后我也用这段代码将新创建的ListBoxItem附加到ListBox控件

Then I also use this code to append the newly created ListBoxItem to the ListBox control

ListBox1.Controls.Add(li);

但它不起作用.我不知道出了什么问题

But its not working. I don't know what am getting wrong

推荐答案

这段代码对我有用

ListBox1.Items.Add(li);

这篇关于如何将新创建的控件附加到 C# 中的另一个控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆