2016-11-07 57 views
0

我有下面的構造函數WPF窗口ViewAssignedStudentsWindowC#WPF的DataGrid設置多項選擇編程

public ViewAssignedStudentsWindow(IEnumerable<StudentDTO> allStudents, MandatoryLessonDTO lesson) 
{ 
    InitializeComponent(); 
    studentsGrid.ItemsSource = allStudents; 
    studentsGrid.SelectedItems.Add(allStudents.Where(x => lesson.StudentIds.Contains(x.Id))); 
} 

StudentDTO具有性能FirstNameLastNameId和其他一些人,這應該不是這個問題很重要。 StudentIdsMandatoryLessonDTO類中的財產是IEnumerable<Guid>,其中包含一些學生的ID。的ViewAssignedStudentWindow的XAML:

<DataGrid SelectionMode="Extended" IsReadOnly="true" HeadersVisibility="Column" ItemsSource="{Binding}" ColumnWidth="*" DockPanel.Dock="Top" Background="White" AutoGenerateColumns="false" x:Name="studentsGrid"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="First name" Binding="{Binding FirstName}" /> 
     <DataGridTextColumn Header="Last name" Binding="{Binding LastName}" /> 
    </DataGrid.Columns> 
</DataGrid> 

的問題是,電網被充滿學生的數據,但是SelectedItems似乎並沒有工作 - 沒有項目被選中。如果我嘗試調試代碼,LINQ似乎會得到正確的結果,但SelectedItems保持空白。我完全失去了這一點,爲什麼這不起作用,它似乎是這樣一個簡單的任務。任何幫助將非常感激。

回答

0

我會在這裏推薦一個DataBinding項目屬性。

學生類:

public class Students : INotifyPropertyChanged { 
    private bool _selected; 
    public bool Selected { 
     get { return _selected; } 
     set { 
      if (value == _selected) return; 
      _selected = value; 
      OnPropertyChanged(); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    [NotifyPropertyChangedInvocator] 
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

添加RowStyle到您的DG:

<DataGrid ... > 
    <DataGrid.RowStyle> 
     <Style TargetType="DataGridRow"> 
      <Setter Property="IsSelected" Value="{Binding Selected}" /> 
     </Style> 
    </DataGrid.RowStyle> 
</DataGrid> 

從代碼隱藏選擇行:

public ViewAssignedStudentsWindow(IEnumerable<StudentDTO> allStudents, MandatoryLessonDTO lesson) 
{ 
    InitializeComponent(); 
    studentsGrid.ItemsSource = allStudents; 
    allStudents.ForEach(x => x.Selected = lesson.StudentIds.Contains(x.Id))); 
}