将userControl添加到列表框中

本文关键字:列表 userControl 添加 | 更新日期: 2023-09-27 18:27:12

我正在为我所在城市的一场比赛做一个小项目。。我刚好撞到了砖墙。问题是:我正在Blend中创建一个userControl(比如说一个画布,我在其中有一个重新绑定…一个文本块和一个图像)。我的问题是,我无法通过代码将其添加到WPF中的listboxitem中。在设计器中一个接一个地添加userControl似乎有效。。但该软件将使用列表框的可变数量的项目。

    private void mainPane1_Loaded(object sender, RoutedEventArgs e)
    {
         MessageBox.Show("layout updated");
        questions cq;
        Button btn;
        for (int i = 1; i <= 10; i++)
        {
            btn = new Button();
            btn.Content = "intreb" + i.ToString();
            cq = new questions();
            Canvas.SetZIndex(cq, 17);
            //cq.questionHolder.Text = "intrebare" + i.ToString();
            listaintrebari.Items.Add(cq);
            MessageBox.Show("intrebare" + i.ToString());
            listaintrebari.Items.Add(btn);
            //MessageBox.Show("layout updated");
        }
    }

questions是我的UserControl,listaintrebari是列表框。我试着添加了一些按钮,效果很好。。。但它似乎讨厌我的userControl。

我正在等待你对如何解决这个问题的想法,如果你对在我的情况下最好使用什么以及如何使用有任何建议。。那就太好了。非常感谢。

将userControl添加到列表框中

好的,这里有一些实际的代码可能会对您有所帮助。我将使用您可能想进一步研究的几个WPF概念:DataBinding、DataTemplates、ImageSources、ObservableCollections

首先,你需要为你的问题创建一个基础类(如果你还没有的话)。你能得到的最简单的东西是这样的:

 internal class Question
 {
     public ImageSource QuestionImage { get; set; }
     public string QuestionText { get; set; }
 }

然后在屏幕后面的代码中(是的,我们还没有到MVVM),您应该创建一个ObservableCollection of Question,并将它们与您的问题放在一起我有这样的smth:

public ObservableCollection<Question> Questions { get; private set; }
public MainWindow()
{
    InitializeComponent();
    this.DataContext = this;
    Questions = new ObservableCollection<Question>();
    for (int i = 1; i <= 10; i++)
    {
        var newQ = new Question { QuestionText = "intrebarea " + i.ToString(), QuestionImage = _get your image as a ImageSource here_ };
        Questions.Add(newQ);
    }
}
  • 这个。DataContext=这非常重要,否则数据绑定将无法工作

在您的设计区域中,创建一个列表并将其绑定到您创建的"问题"集合。问题在列表中的显示方式由"ItemTemlpate"驱动,如下所示。

<ListBox ItemsSource="{Binding Questions}">
  <ListBox.ItemTemplate>
    <StackPanel>
      <Image Source="{Binding QuestionImage}" Height="20" Width="20"/>
      <TextBlock Margin="5" Text="{Binding QuestionText}" />
    </StackPanel>
  </ListBox.ItemTemplate>
</ListBox>
  • 您可以用UserControl内容或事件UserControl本身替换那里的I,但请确保保留Question类中对象的绑定

就像我上面说的,很多事情在这一点上可能没有意义,所以一定要阅读它们:什么是数据绑定,什么是DataContext,什么是ObservableCollection。此外,当你有机会的时候,试着看看MVVM。。。

最后,如果你不确定当你的项目中有jpg或png文件时如何获得ImageSource:

public ImageSource GetImagesource(string location)
{
  var res = new BitmapImage()
  res.BeginInit();
  res.UriSource = new Uri("pack://application:,,,/ApplicationName;component/" + location);
  res.EndInit();
  return res;
}

正确的处理这种情况的方法是建立一个包含问题集合的数据模型。然后将ListBox.ItemsSource绑定到集合,并提供一个使用UserControl的DataTemplate。

使用ListBox的ItemTemplate定义对象的每个实例的外观,然后将ListBox的ItemsSource绑定到该类型的集合。

您需要创建控件的集合(例如List),并将该集合绑定到ListBox。