我正在为 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/ 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)