如何将标签的ItemsControl绑定到ObservableCollection

时间:2018-03-21 12:12:06

标签: c# wpf mvvm

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

值得注意的是,这个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>

这是我的StudentsActivities课程:

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 });
  }
 }
}

1 个答案:

答案 0 :(得分:0)

更改

<ItemsControl ItemsSource={StudentCollection}">

<ItemsControl ItemsSource={Binding StudentCollection}">

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

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

不需要最后一次更改,但也没有必要。