[英]Get Checkbox value in Datagrid bound to an ItemsSource in wpf
在WPF中,我创建了一个与ItemsSource绑定的Datagrid,然后添加了另一个未与ItemsSource绑定的列。 我试图遍历Datagrid中的行并获取复选框值(true或false)。 这是我的Datagrid的一个片段:
<DataGridTemplateColumn x:Name="CheckBoxColumn" Width="Auto">
<DataGridTemplateColumn.Header>
<CheckBox Content="Select All" Style="{StaticResource StdCheckBoxStyle}" x:Name="headerCheckBox"/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="checkBoxRow" Margin="45 2 0 0" Style="{StaticResource StdCheckBoxStyle}"
IsChecked="{Binding IsChecked, ElementName=headerCheckBox,
Mode=OneWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding Index, Mode=OneWay}" IsReadOnly="True" Width="Auto" Header="Index"/>
Datagrid绑定到ItemsSource,这是MyObject的ICollection。 这是我在后面的代码中所做的:
public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row) yield return row;
}
}
private void OnUpdate(object obj)
{
var rows= GetDataGridRows(MyDatagrid);
foreach (DataGridRow r in rows)
{
DataRowView rv = (DataRowView)r.Item;
foreach (DataGridColumn column in MyDatagrid.Columns)
{
if (column.GetCellContent(r) is CheckBox)
{
CheckBox cellContent = column.GetCellContent(r) as CheckBox;
//do something
}
}
}
}
但是在运行这段代码后,我得到一个异常:
Unable to cast object of type '...MyObject' to type 'System.Data.DatarowView'.
我看了一下,发现在MSDN中:
the DataItem property of the GridViewRow "Gets the underlying data object to which the GridViewRow object is bound."
我知道这个问题,我知道原因,但是找不到解决方法。 感谢您的关注。
在您的代码中,例外:
Unable to cast object of type '...MyObject' to type 'System.Data.DatarowView'.
由于此行而引发:
DataRowView rv = (DataRowView)r.Item;
这意味着r.item对象的类型为MyObject。 强制转换无效。 改用:
MyObject rv= r.Item;
[编辑]答案的第一部分仅解决了异常问题。 您必须将datagrid转换为datagridview。 要访问单元格的内容:
foreach (DataGridViewRow r in MyDataGridView.Rows)
{
foreach (DataGridViewCell c in r.Cells)
{
if (c.Value is CheckBox)
{
CheckBox cellContent = c.Value as Checkbox;
//do something
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.