user8210624
user8210624

Reputation:

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?

Upvotes: 0

Views: 6935

Answers (2)

krishna
krishna

Reputation: 261

private void ChkSelect_Checked(object sender, RoutedEventArgs e)
    {
        DataRowView row;
        row = (DataRowView)((CheckBox)e.OriginalSource).DataContext;
        row["DeleteRule"] = "True";
    }

    private void ChkSelect_Unchecked(object sender, RoutedEventArgs e)
    {
        DataRowView row;
        row = (DataRowView)((CheckBox)e.OriginalSource).DataContext;
        row["DeleteRule"] = "False";
    }

This solution is without Binding ,you can get the checked row with the above code

Upvotes: 1

mm8
mm8

Reputation: 169400

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.

Upvotes: 3

Related Questions