我正在为 WPF数据网格中的单个单元格提供自动化ID,但我遇到了一些麻烦.我决定尝试根据它们在网格中的位置命名单元格(行索引和列索引).使用UI检查器并突出显示有问题的DataGridCell之一
GridItem.Row:2
GridItem.Column:0
…这让我相信我可以通过绑定访问这些属性.但是,过去几天我花了大部分时间梳理互联网,以了解如何解决这个问题,但没有找到任何结果.
当前的XAML代码如下(‘???’是占位符):
<DataGrid.CellStyle> <Style TargetType="{x:Type DataGridCell}"> <Setter Property="AutomationProperties.AutomationId"> <Setter.Value> <MultiBinding StringFormat="cell:{0}-{1}"> <Binding ??? /> <Binding ??? /> </MultiBinding> </Setter.Value> </Setter> </Style> </DataGrid.CellStyle>
是否存在这些属性的路径?或者是否存在另一种方法来为单个单元格提供唯一的自动化ID?我对WPF和XAML不是很有经验,所以任何指针都很受欢迎.
提前致谢.
终于搞定了.在此发布解决方案,以便其他人可以受益.背后的代码(基于http://gregandora.wordpress.com/2011/01/11/wpf-4-datagrid-getting-the-row-number-into-the-rowheader/):
Private Sub DataGrid_LoadingRow(sender As System.Object, e As System.Windows.Controls.DataGridRowEventArgs) e.Row.Tag = (e.Row.GetIndex()).ToString() End Sub
和XAML:
<DataGrid ... LoadingRow="DataGrid_LoadingRow" > <DataGrid.ItemContainerStyle> <Style TargetType="{x:Type DataGridRow}"> <Setter Property="AutomationProperties.AutomationId"> <Setter.Value> <MultiBinding StringFormat="Row{0}"> <Binding Path="(DataGridRow.Tag)" RelativeSource="{RelativeSource Mode=Self}" /> </MultiBinding> </Setter.Value> </Setter> <Setter Property="AutomationProperties.Name"> <Setter.Value> <MultiBinding StringFormat="Row{0}"> <Binding Path="(DataGridRow.Tag)" RelativeSource="{RelativeSource Mode=Self}" /> </MultiBinding> </Setter.Value> </Setter> </Style> </DataGrid.ItemContainerStyle> ... <DataGrid.CellStyle> <Style> <Setter Property="AutomationProperties.AutomationId"> <Setter.Value> <MultiBinding StringFormat="cell{0}Col{1}"> <!-- bind to row automation name (which contains row index) --> <Binding Path="(AutomationProperties.Name)" RelativeSource="{RelativeSource AncestorType=DataGridRow}" /> <!-- bind to column index --> <Binding Path="(DataGridCell.TabIndex)" RelativeSource="{RelativeSource Mode=Self}" /> </MultiBinding> </Setter.Value> </Setter> </Style> </DataGrid.CellStyle> ... </DataGrid>