【问题标题】:How to bind ItemsControl of Labels to an ObservableCollection如何将标签的 ItemsControl 绑定到 ObservableCollection
【发布时间】:2018-03-21 12:12:05
【问题描述】:

我有一个 ItemsControl,它的 ItemsSource 是 ObservableCollection。 DataTemplate 包含标签控件。我的目标是将每个标签的内容属性设置为 ObservableCollection 中的元素,但现在,每个标签的内容都是空白的。

值得注意的是,这个 ItemsControl 嵌套在另一个父 ItemsControl 中,但让我展示一下:

<ItemsControl ItemsSource={Binding StudentCollection}">
 <ItemsControl.ItemTemplate> 
  <DataTemplate>
   <Grid>
    <Grid.ColumnDefinitions>
     <ColumnDefinition Width="90"/>
     <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    // This is the ItemsControl that is not working properly with the Labels


   <ItemsControl ItemsSource="{Binding StudentActivitiesCollection}">
    <ItemsControl.ItemTemplate>
     <DataTemplate>
      <Label Content="{Binding Sport, UpdatedSourceTrigger=PropertyChanged}"/>
     </DataTemplate>
    </ItemsControl.ItemTemplate>
   </ItemsControl>
  </Grid>
 </DataTemplate>
 </ItemsControl.Template>
</ItemsControl>

这是我的 StudentActivity 课程:

public class StudentActivities : INotifyPropertyChanged

  private string sport;
  public string Sport
  {
    get
    {
     return this.sport;
    }
    set
    {
     this.sport = value;
     OnPropertyChanged("Sport");
    }
   }
  }
}

还有我的工作视图模型:

 private ObservableCollection<StudentActivities> studentActivitiesCollection;
 public ObservableCollection<StudentActivities> StudentActivitiesCollection
 {
  get
  {
   if (studentActivitiesCollection == null)
      studentActivitiesCollection = new ObservableCollection<StudentActivities>();
    return studentActivitiesCollection;
   }
  }

这是我用来在 ViewModel 中填充 ObservableCollection 的方法:

private void PopulateStudentActivitiesCollection(ObservableCollection<Student> Students)
{
 foreach (Student s in Students)
 {
   StudentActivitiesCollection.Add(new StudentActivities () { Sport = StudentSport });
  }
 }
}

【问题讨论】:

  • 我更新了我的帖子,抱歉。
  • 请发布您的课程。什么是 StudentCollection?

标签: c# wpf mvvm


【解决方案1】:

改变

<ItemsControl ItemsSource={StudentCollection}">

<ItemsControl ItemsSource={Binding StudentCollection}">

<Label Content="{Binding Sport, UpdatedSourceTrigger=PropertyChanged}"/>

<Label Content="{Binding Sport}"/>

最后一次更改不是必需的,但也不是必需的。

【讨论】:

  • 我添加了一些代码供参考,我有 StudentCollection 的绑定,我只是忘记复制它。我更新了我的帖子。
猜你喜欢
  • 2012-07-04
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
  • 2017-02-25
  • 1970-01-01
相关资源
最近更新 更多