I’ve faced strange issue with Silverlight DataGrid.
When I’m binding list of structs (placed in ViewModel) to grid values are displayed properly, but for some reason changes that are made to grid are not reflected in ViewModel.
public struct ObjectSelection
{
public bool Selected { get; set; }
public string Name { get; set; }
}
public List<ObjectSelection> SelectedObjects
{
get { return _selectedObjects; }
set
{
if (value != _selectedObjects)
{
_selectedObjects= value;
FirePropertyChanged("SelectedObjects");
}
}
}
XAML:
<navigation:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding SelectedObjects, Mode=TwoWay}"
<navigation:DataGrid.Columns>
<navigation:DataGridFilterTemplateColumn Header="Selected"
CanUserFilter="True"
CanUserSort="False"
DataType="Boolean"
SortMemberPath="Include">
<navigation:DataGridFilterTemplateColumn.CellTemplate>
<DataTemplate>
<controls:CheckBox HorizontalAlignment="Center"
VerticalAlignment="Center"
IsChecked="{Binding Selected, Mode=TwoWay}"/>
</DataTemplate>
</navigation:DataGridFilterTemplateColumn.CellTemplate>
</navigation:DataGridFilterTemplateColumn>
<navigation:DataGridFilterColumn Header="Dimension"
DataType="String"
CanUserFilter="False"
IsReadOnly="True"
Binding="{Binding Name}"
CanUserSort="True"
SortMemberPath="Name"
Width="*"/>
</navigation:DataGrid.Columns>
</navigation:DataGrid>
You shouldn’t define
ObjectSelectionasstruct.A
structis copied every time it is read from your property. That copy is used for binding. If that copy is then modified by the user, the original remains unchanged. I suggest you use aclassinstead of astruct. In almost all cases, classes are the better choice.Microsofts recommendation: