I am trying to create a DataGrid inside a WPF DataGrid's RowDetailsTemplate.
I have a collection of Jobs. Each Job can have one or more Employees assigned to it:
public class Job : _Base
{
private string _JobName = string.Empty;
public string JobName
{
get { return _JobName; }
set
{
if (_JobName != value)
{
_JobName = value;
RaisePropertyChanged("JobName");
}
}
}
private string _JobNumber = string.Empty;
public string JobNumber
{
get { return _JobNumber; }
set
{
if (_JobNumber != value)
{
_JobNumber = value;
RaisePropertyChanged("JobNumber");
}
}
}
private ObservableCollection<Employee> _Employees;
public ObservableCollection<Employee> Employees
{
get { return _Employees; }
set
{
if (_Employees != value)
{
if (_Employees != value)
{
_Employees = value;
RaisePropertyChanged("Employees");
}
}
}
}
public Job()
{
Employees = new ObservableCollection<Employee>();
}
}
and
public class Employee : _Base
{
private string _EmployeeName = string.Empty;
public string EmployeeName
{
get { return _EmployeeName; }
set
{
if (_EmployeeName != value)
{
_EmployeeName = value;
RaisePropertyChanged("EmployeeName");
}
}
}
private bool _IsChecked = false;
public bool IsChecked
{
get { return _IsChecked; }
set
{
if (_IsChecked != value)
{
_IsChecked = value;
RaisePropertyChanged("IsChecked");
}
}
}
}
and my XAML:
<DataGrid ItemsSource="{Binding Jobs}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Job Name" Binding="{Binding JobName}" />
<DataGridTextColumn Header="Job Number" Binding="{Binding JobNumber}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding Employees}"
AutoGenerateColumns="False">
<DataGridCheckBoxColumn Binding="{Binding IsChecked}"/>
<DataGridTextColumn Binding="{Binding EmployeeName}"/>
</DataGrid>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
When I run this and click a row, I get:
Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead
If I remove the inner grid's column definitions, then it doesn't error. But then it's generating the columns by itself. I need to specify the columns myself.
What is wrong here?
You need to define your inner datagrid's columns correctly
<DataGrid ItemsSource="{Binding Employees}" AutoGenerateColumns="False">
<DataGridCheckBoxColumn Binding="{Binding IsChecked}"/>
<DataGridTextColumn Binding="{Binding EmployeeName}"/>
</DataGrid>
Turn this to
<DataGrid ItemsSource="{Binding Employees}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsChecked}"/>
<DataGridTextColumn Binding="{Binding EmployeeName}"/>
</DataGrid.Columns>
</DataGrid>
Essentially setting it the way you are is attempting to set the source in the xaml and then bind it to another source through ItemsSource
which is where the error is coming from.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With