WPF Datagrid checkbox column checked

My datagrid checkbox column:

                    <DataGridTemplateColumn MaxWidth="45">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox x:Name="check_tutar"  VerticalAlignment="Center" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Checked="check_tutar_Checked"></CheckBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

I want to access this checkbox and change checked property. I try defalut method: check_tutar.IsChecked = false;

But didnt work because I can not access the checkbox using name. How can I change datagrid column checkbox checked property?


You should bind the IsChecked property of the CheckBox to a bool property of your data object and set this property instead of trying to access the CheckBox control itself:

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <CheckBox x:Name="check_tutar" IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" />
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

The data class should implement the INotifyPropertyChanged interface and raise change notifications whenever the IsChecked property is set for this to work:

public class YourClass : INotifyPropertyChanged
{
    private bool _isChecked;
    public bool IsChecked
    {
        get { return _isChecked; }
        set { _isChecked = value; NotifyPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

You could then simply check/uncheck the CheckBox of a row of in the DataGrid, by setting the IsChecked property of the corresponding object, e.g:

List<YourClass> theItems = new List<YourClass>(0) { ... };
dataGrid1.ItemsSource = theItems;

//check the first row:
theItems[0].IsChecked = true;

This is basically how WPF and the DataGrid works.