将userControl添加到列表框

我正在为我的城市竞赛做一个小项目……我只是碰到了一堵砖墙。事情是:我在Blend中创建一个userControl(让我们说一个canvas,我有一个反应角…一个文本块。我的问题是我无法通过代码将其添加到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"); } } 

问题是我的UserControl和listaintrebari是列表框。我试图添加一些按钮,它工作得很好……但它似乎讨厌我的userControl。

我正在等待你对如何解决这个问题的想法,如果你对我的情况下最适合使用的其他东西有任何想法,那将会很棒。谢谢你!

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

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

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

然后在你的屏幕后面的代码中(是的,我们还没有在MVVM上),你应该创建一个ObservableCollection的问题,然后用我的问题来解决它们:

 public ObservableCollection Questions { get; private set; } public MainWindow() { InitializeComponent(); this.DataContext = this; Questions = new ObservableCollection(); 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); } } 
  • this.DataContext =这非常重要,否则您的数据绑定将无法正常工作。

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

         
  • 您可以将UserControl内容或事件替换为UserControl本身,但请确保将Bindings保留到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。