mardi 19 novembre 2019

DataGrid a single row checkbox is selecting all rows

I am having this issue implementing a checkbox per row. What happens is that when I click on a single checkbox it then checks/unchecks all other checkboxes in my datagrid. I think what may be happening is that I am recreating a checkbox with the same default id. maybe.

Here is my xaml and how I am creating my datagrid with my problem column:

<DataGrid
            ItemsSource="{Binding Pets, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
            SelectedItem="{Binding SelectedPet, Mode=TwoWay}"
            AutoGenerateColumns="False"
                HorizontalAlignment="Left"
                BorderThickness="1"
                CanUserAddRows="False"
                CanUserDeleteRows="False"
                RowHeaderWidth="0"
                MinRowHeight = "25"
                ColumnHeaderHeight="30"
                HorizontalGridLinesBrush="Black"
                VerticalGridLinesBrush="Black"
                Foreground="Black" 
                CanUserSortColumns="True"
                SelectionMode="Single"
                RowStyle="{Binding Mode=OneWay, Source={StaticResource DefaultRowStyle}}">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Selection" SortMemberPath="Station" MinWidth="20">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" >
                                <CheckBox IsChecked="{Binding Path=DataContext.IsPetChecked, RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"/>
                                <TextBlock Text="{Binding PetName, Mode=OneWay}"/>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <!--MORE Columns below-->
            </DataGrid.Columns>
        </DataGrid>

In my view model this is how I have my observable collection and my checkbox

public bool IsPetChecked
{
    get
    {
        return _isPetChecked;
    }
    set
    {
        if (_isPetChecked != value)
        {
            _isPetChecked = value;
            RaisePropertyChanged(nameof(IsPetChecked));
        }
   }
}
private bool _isPetChecked = false;

/// <summary>
/// Stores the collection of pets
/// </summary>
public ObservableCollection<Pet> Pets
{
    get
    {
        return _pets;
    }
    set
    {
        _pets = value;
        RaisePropertyChanged(nameof(Pets));
    }
}
private ObservableCollection<Pet> _pets = new ObservableCollection<Pet>();

When I click on the checkbox the property is marked as changed but I am seeing it check all other checkboxes. Can someone tell me what am I doing wrong? Many thanks in advance.




Aucun commentaire:

Enregistrer un commentaire