我想使用c#将新创建的控件附加到ListBoxItem控件

时间:2019-01-17 02:08:56

标签: c# xaml

我仍然是VS,C#和XAML的新手。因此,我从以前的question获得了有关如何将子控件添加到listBox的代码。

JOIN

我尝试使用相同的模式将子控件添加到ListBoxItem控件中,但是它不起作用,因此我使用了此方法,它没有引发任何错误,但是我的应用程序需要花费全年的时间

NULL

我不知道这样做是否正确。

我的问题:我想向新创建的ListBox1.Items.Add(li); 中添加一个li.Children.Add(img); 控件。这是我的下面的代码

Image

我也将要创建一个ListBoxItem控件并将其添加到新创建的foreach (var imgPath in filePaths) { WrapPanel li = new WrapPanel(); 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; Image img = new Image(); img.Width = 150; img.Height = 150; img.VerticalAlignment = System.Windows.VerticalAlignment.Top; img.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; BitmapImage imgSrc = new BitmapImage(); imgSrc.BeginInit(); imgSrc.UriSource = new Uri(imgPath, UriKind.Relative); imgSrc.EndInit(); img.Source = imgSrc; li.Children.Add(img); // This is where my problem is ListBox1.Items.Add(li); }

TextBlock

因此,我也想知道是否要使用与添加ListBoxItem相同的代码添加TextBlock textBlk = new TextBlock(); textBlk.Width = 150; textBlk.Height = 50; textBlk.VerticalAlignment = System.Windows.VerticalAlignment.Bottom; textBlk.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; 控件。我想用C#来做所有的事情

我的想法:MS为什么不让C#像JavaScript一样容易?

1 个答案:

答案 0 :(得分:0)

我尝试了此代码并开始工作

// Codebehind 
foreach (var imgPath in filePaths)
{
    var li = new WrapPanel
    {
        Width = 150,
        Height = 200,
        Margin = new Thickness(5),
        VerticalAlignment = VerticalAlignment.Top,
        HorizontalAlignment = HorizontalAlignment.Left,
        Background = Brushes.DarkBlue
    };

    var img = new Image
    {
        Width = 150,
        Height = 150,
        VerticalAlignment = VerticalAlignment.Top,
        HorizontalAlignment = HorizontalAlignment.Stretch,
        Source = new BitmapImage(new Uri(imgPath, UriKind.RelativeOrAbsolute)) // this is the main difference with your version 
    };

    li.Children.Add(img);

    var textBlk = new TextBlock
    {
        Width = 150,
        Height = 50,
        VerticalAlignment = VerticalAlignment.Bottom,
        HorizontalAlignment = HorizontalAlignment.Stretch,
        Background = Brushes.Aqua,
        Text = "Test text"
    };

    li.Children.Add(textBlk);

    ListBox1.Items.Add(li);
}

查看

<ListBox x:Name="ListBox1" />