You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataGrid项的AutomationProperties.Name无法修改问题求助

解决DataGrid内部项AutomationProperties.Name不生效的问题

我之前也碰到过这个情况!DataGrid默认会把数据对象的类名作为自动化名称,咱们可以通过以下几种方式强制指定想要的属性值:

1. 给单元格内部元素设置自动化名称

因为DataGridTextColumn的ElementStyle是作用于列内的TextBlock的,直接在这个样式里添加AutomationProperties.Name的绑定就能覆盖默认值:

<Style x:Key="DataGridTextCellStyle" TargetType="TextBlock">
    <!-- 你的其他样式设置,比如字体、对齐等 -->
    <Setter Property="AutomationProperties.Name" Value="{Binding Name}" />
</Style>

这样每个单元格里的TextBlock都会把数据项的Name属性作为自动化名称,自动化框架会优先读取这个值,而不是默认的类名。

2. 给整行设置自动化名称

如果需要给整个DataGrid行指定自动化名称,可以在DataGrid.RowStyle里设置:

<DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="AutomationProperties.Name" Value="{Binding Name}" />
        </Style>
    </DataGrid.RowStyle>
    <!-- 你的列定义 -->
</DataGrid>

为什么默认不生效?

这是因为DataGrid的自动化对等类(比如DataGridCellAutomationPeer)默认逻辑是:如果单元格内部元素没有显式设置AutomationProperties.Name,就会使用数据对象的类型名称或者ToString()结果。所以咱们只要在内部元素上显式绑定,就能覆盖这个默认行为。

内容的提问来源于stack exchange,提问作者Ahmed Abdo Ortiga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:25:58