Hei,
I need help figuring out how to access checkbox in wpf datagrid header. Here's what i have:
<DataGrid.Columns>
<DataGridTemplateColumn CanUserReorder="False" CanUserResize="False">
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<CheckBox Name="cbxAll" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" />
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Checked, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding Path=NoErrors}" Name="theCheckbox" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
I have set the Name
for the checkbox, but for some reason i cant access it from on the code side.
I need to access the checkbox to uncheck it after i refresh my datagrid items. How can i do this?
A working example in MVVM:
ViewModel
public class MainWindowViewModel : INotifyPropertyChanged
{
private bool allItemsAreChecked;
public event PropertyChangedEventHandler PropertyChanged;
public bool AllItemsAreChecked
{
get
{
return this.allItemsAreChecked;
}
set
{
this.allItemsAreChecked = value;
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs("AllItemsAreChecked"));
}
}
}
}
XAML
<DataGridTemplateColumn CanUserReorder="False" CanUserResize="False">
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}},
Path=DataContext.AllItemsAreChecked}" />
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
</DataGridTemplateColumn>
Allthough binding might be the way you should go, it is possible to do what you ask. Here's one way of doing it:
1.Give your header CheckBox
an Uid
<CheckBox Uid="CheckAll" />
2.Name your DataGrid
<DataGrid Name="myDataGrid" />
3.Implement the following extension method
public static UIElement FindUid(this DependencyObject parent, string uid)
{
var count = VisualTreeHelper.GetChildrenCount(parent);
if (count == 0) return null;
for (int i = 0; i < count; i++)
{
var el = VisualTreeHelper.GetChild(parent, i) as UIElement;
if (el == null) continue;
if (el.Uid == uid) return el;
el = el.FindUid(uid);
if (el != null) return el;
}
return null;
}
4.Access and uncheck the CheckBox
in code behind like this
CheckBox checkBox = myDataGrid.FindUid("CheckAll") as CheckBox;
checkBox.IsChecked = false;
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