我想在DataGrid中获取CheckBoxColumn的值wpf
我试试这段代码
foreach (spShowTotal_Result item in dgShowStudent.ItemsSource)
{
bool? check = ((CheckBox)dgShowStudent.Columns[0].GetCellContent(item)).IsChecked;
}
但出现此异常
无法将“System.Windows.Controls.ContentPresenter”类型的对象强制转换为“System.Windows.Controls.CheckBox”。
答案 0 :(得分:2)
似乎评论中提供的解决方法不适合您。让我以不同的方式解决这个问题。
将DataGrid
视为
<DataGrid x:Name="datagridexec">
<DataGridTemplateColumn Header="DUT">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="checkboxinstance"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid>
在您的xaml.cs
中,您可以访问以下内容
List<CheckBox> checkBoxlist = new List<CheckBox>();
// Find all elements
FindChildGroup<CheckBox>(datagridexec, "checkboxinstance", ref checkBoxlist );
foreach (CheckBox c in checkBoxlist)
{
if (c.IsChecked)
{
//do whatever you want
}
}
您需要以下类来遍历树。
public static void FindChildGroup<T>(DependencyObject parent, string childName, ref List<T> list) where T : DependencyObject
{
// Checks should be made, but preferably one time before calling.
// And here it is assumed that the programmer has taken into
// account all of these conditions and checks are not needed.
//if ((parent == null) || (childName == null) || (<Type T is not inheritable from FrameworkElement>))
//{
// return;
//}
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
// Get the child
var child = VisualTreeHelper.GetChild(parent, i);
// Compare on conformity the type
T child_Test = child as T;
// Not compare - go next
if (child_Test == null)
{
// Go the deep
FindChildGroup<T>(child, childName, ref list);
}
else
{
// If match, then check the name of the item
FrameworkElement child_Element = child_Test as FrameworkElement;
if (child_Element.Name == childName)
{
// Found
list.Add(child_Test);
}
// We are looking for further, perhaps there are
// children with the same name
FindChildGroup<T>(child, childName, ref list);
}
}
return;
}
参考:How to access datagrid template column textbox text WPF C#