平,
我需要帮助找出如何访问wpf datagrid标头中的复选框。这就是我所拥有的:
<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>
我为复选框设置了Name
,但出于某种原因,我无法从代码端访问它。
我需要在刷新数据网格项后访问该复选框以取消选中它。我怎么能这样做?
答案 0 :(得分:9)
MVVM中的一个工作示例:
<强>视图模型强>
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>
答案 1 :(得分:3)
虽然绑定可能是您应该采取的方式,但您可以按照自己的要求行事。 这是一种方法:
1.给你的标题CheckBox
一个Uid
<CheckBox Uid="CheckAll" />
2.为您的DataGrid
<DataGrid Name="myDataGrid" />
3.实现以下扩展方法
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.访问并取消选中代码中的CheckBox
,如下所示
CheckBox checkBox = myDataGrid.FindUid("CheckAll") as CheckBox;
checkBox.IsChecked = false;
答案 2 :(得分:0)
设置一个简单的事件:
<CheckBox x:Name="cbxAll" Click="cbxAll_Click"/>
在事件中单击代码:
private void cbxAll_Click(object sender, RoutedEventArgs e)
{
var ckbox = sender as CheckBox;
if (ckbox.IsChecked == true)
{
//Check all itens
}
else
{
//Uncheck all itens
}
}
注意:发件人是复选框