Files
microsoft-ui-xaml/controls/dev/TableView/TableViewColumnHeaderAutomationPeer.cpp
T
Hitesh KumarandCopilot d5132fd2e4 TableView: templated column headers, UIA resize, sort fixes, recycle perf, theming (#12307)
## Fixes

| Internal issue | Type | Change |
|---|---|---|
| https://task.ms/64475625 | Bug | Column headers are a templated,
restylable `TableViewColumnHeader` with visual states |
| https://task.ms/64475623 | Bug | Header typography comes from the
header Style, not C++ local values |
| https://task.ms/64143451 | Bug | Header column separators are always
drawn (no new property); hide them by overriding
`TabularSurfaceHeaderSeparatorBrush` |
| https://task.ms/63996584 | Task | Column headers expose the UIA
Transform pattern so UIA clients can resize columns |
| https://task.ms/64475611 | Bug | Outer border uses new
`TabularSurfaceOuterBorderBrush` (`CardStrokeColorDefault`); grid-line
values were in #12349 |
| https://task.ms/64475629 | Bug | Default group header uses theme
tokens (SemiBold key style, 8px spacing); the item count inherits the
header `Foreground` |
| https://task.ms/64652961 | Task | Row recycling no longer regenerates
cells or refreshes row chrome twice (scroll performance) |
| https://task.ms/63790855 | Task | Sort: `CanSort` is enforced and
`SortByColumn(column, None)` always clears; a sort through a source
another table owns returns false; no spurious `Sorted`; an app-owned
sort survives a `CanSort`/`CanUserSortColumns` opt-out |
| https://task.ms/63787021 | Task | Cell automation-peer constructor
validates its arguments; `BeginEdit` rolls back when it throws |

Not changed: https://task.ms/64512732 (by design: Auto columns follow
content width), https://task.ms/64475627 (design decision: keep chevron
sort glyphs), https://task.ms/64513223 (investigation only; fix
deferred).

## PR Type

- [x] Bugfix
- [x] Feature
- [ ] Code style update (formatting, renaming)
- [ ] Refactoring (no functional changes, no API changes)
- [ ] Build related changes
- [x] Documentation content changes
- [ ] Other (please describe):

## Description

Follow-up to #12349 (merged) and #12285.

Column headers move from code-built Grids to a new templated
`TableViewColumnHeader`, restylable through
`TableView.ColumnHeaderStyle` or `TableViewColumn.HeaderStyle`. Header
peers gain the UIA Transform pattern for column resize. Sort behavior is
tightened around `CanSort`, opt-outs and shared `TableViewSource`
ownership. Row recycling reuses cells. Outer border, header lines and
the default group header follow Fluent tokens.

Review-driven fixes included here:
- The header Style's `TargetType` `TypeName` is kept alive while it is
compared; a Style with only `BasedOn` typed is applied, and its setters
are read before applying it seals the Style. Incompatible, untyped or
cyclic `BasedOn` Styles are ignored with a debug diagnostic.
- A header disabled by its Style reports `IsEnabled=false` and is not
invokable through UIA.
- UIA `Transform.Resize` converts physical pixels through the table's
full visual scale (not only `RasterizationScale`), and a width change
below the drag jitter deadband is written once, exactly.
- Disabling a header in its High Contrast hover/pressed state keeps the
disabled foreground (state order fixed); the disabled sort glyph follows
the text brush across theme changes.
- A `CanSort` opt-out made inside `BeginningEdit` is replayed after the
edit it let open closes, and rebuilds headers even when a `Sorted`
handler throws.
- Header rebuilds caused by `Content`/`Header` or `Columns` changes keep
focus in the header band, respect an app's own focus move, and release
`UIElement` headers back to the app.
- A disabled group header does not dim its item count twice. The count
opacity follows `ContentTemplate` changes while the header is disabled.

<details><summary>Product changes by file</summary>

| File | +/- | What changed | Items |
|---|---|---|---|
| `TableView/TableView.cpp` (+ .h) | +684 / −382 | `RebuildHeaders`
creates `TableViewColumnHeader` controls; applies
`ColumnHeaderStyle`/`HeaderStyle` with TargetType/BasedOn checks;
density MinHeight/Padding only when the Style doesn't set
them<br>`ReleaseHeaderCells` and header-focus handling for
removed/replaced columns, re-entrant rebuilds and app focus
moves<br>Header bottom rule thickness set on `PART_HeaderRow`; header
lines no longer follow `GridLinesVisibility`<br>Row prepare/clear
refresh chrome once; `TryResizeColumnFromAutomation` writes small widths
exactly | 64475625, 64475623, 64143451, 64652961, 63996584, 63790855 |
| `TableView/TableViewColumnHeader.cpp` (+ .h; replaces
`TableViewHeaderCell.h`) | +435 / −210 | New sealed templated
`ContentControl` with read-only `Column`<br>Resolves
`PART_ContentPresenter`, `PART_GridLine`, `PART_SortIndicatorHost`,
`PART_ResizeGripperHost`; hosts the sort glyph and gripper<br>Drives
`CommonStates`/`HighContrastStates`/`SortStates`; disabled sort glyph
bound to the text brush | 64475625, 64475623 |
| `TableView/TableViewRow.cpp` (+ .h) | +191 / −35 | Recycled rows keep
their cells unless cell automation peers exist; chrome refreshed once;
tooltips re-applied on recycle<br>`BeginCellEdit` restores display
element, edit state and focus on throw | 64652961, 63787021 |
| `TableView/TableView.xaml` | +128 / −18 | Default
`TableViewColumnHeader` Style/template: typography setters, visual
states, parts<br>Outer border uses `TabularSurfaceOuterBorderBrush`;
header lines use `TabularSurfaceHeaderSeparatorBrush`<br>Group header:
`TableViewGroupExpanderSpacing` (8), padding 8,8,12,8, key/count text
styles, count inherits `Foreground` | 64475625, 64475623, 64475611,
64475629 |
| `TableView/TableViewColumnHeaderAutomationPeer.cpp` (+ .h) | +127 / −9
| `ITransformProvider`: `Resize` converts physical px through the visual
scale; `CanResize` tracks gripper availability (pinned →
false)<br>`IsEnabled` follows the header; name read from the content
presenter | 63996584, 64475625 |
| `TableView/TableView_Sort.cpp` | +113 / −39 | `SortByColumn(None)`
bypasses the `CanSort` gate; other sorts refused<br>Sort through a
source owned by another table returns false; implicit clears keep the
app's sort and raise no `Sorted`; app-lit columns left alone on opt-out
| 63790855 |
| `TableView/TableView_Layout.cpp` | +74 / −14 | Realized-row walk only
when a visible Auto column exists<br>Transform `CanResize` changes
raised for existing header peers | 64652961, 63996584 |
| `TableView/TableView_Editing.cpp` | +63 / −15 | `BeginEdit` unwinds on
throw; `CanSort` opt-out during `BeginningEdit` queued until the edit
closes | 63787021, 63790855 |
| `TableView/TableViewCellAutomationPeer.cpp` (+ .h, `TableViewCell.h`)
| +48 / −0 | Public constructor throws `E_INVALIDARG` for null args,
negative/out-of-range index or a foreign column; internal path uses
`TrustedOwnerTag` | 63787021 |
| `TableView/TableViewGroupHeader.cpp` (+ .h) | +39 / −0 | Default
count's opacity is not applied twice when disabled | 64475629 |
| `TableView/TableView.idl` | +31 / −13 | `TableViewColumnHeader`,
`TableView.ColumnHeaderStyle`,
`TableViewColumn.HeaderStyle`<br>`CanSort`/`SortByColumn`/`ToggleSortDirection`/`GridLinesVisibility`
docs; cell-peer `E_INVALIDARG`; group-header parts | 64475625, 63790855,
64143451, 63787021 |
| `TableView/TableView_Columns.cpp` | +19 / −0 | Releases removed
columns' header cells; old `UIElement` `Header` returned to the app on
change | 64475625 |
| `TableView/TableViewColumn.cpp` | +7 / −0 | `HeaderStyle` change
queues a header rebuild | 64475625 |
| `TableView/TableViewSource.h` | +6 / −0 | `IsOwnedByOther` helper for
sort sync | 63790855 |
| `CommonStyles/TabularSurfaces_themeresources.xaml` | +5 / −2 | New
`TabularSurfaceOuterBorderBrush` (Dark/Light/HC); group count opacity
documented as secondary-over-primary text (0.77 Dark) | 64475611,
64475629 |
| `TableView/TableView.vcxitems` | +2 / −1 | Swap
`TableViewHeaderCell.h` for `TableViewColumnHeader.*` | 64475625 |
| Generated / metadata (`Generated/TableView.properties.*`,
`Generated/TableViewColumn.properties.*`,
`dll-tabular/XamlMetadataProviderGenerated.h`) | +123 / −0 | Codegen for
the new properties and type | 64475625 |

**Total: 17 rows, 29 product files, +2117 / −738.** Also: 19 test files
(+3718 / −32), 3 docs (+161 / −35), 6 sample files (+2 / −9).

</details>

### New preview API (needs API review)

- **`TableViewColumnHeader`**: sealed, templated `ContentControl`,
created only by `TableView`.
  - Read-only `Column` property.
- Template parts (optional): `PART_ContentPresenter`, `PART_GridLine`,
`PART_SortIndicatorHost`, `PART_ResizeGripperHost`.
- Visual state groups: `CommonStates`, `HighContrastStates`,
`SortStates`.
- **`TableView.ColumnHeaderStyle`**: Style applied to every column
header.
- **`TableViewColumn.HeaderStyle`**: per-column Style; wins over
`TableView.ColumnHeaderStyle`.

There is no `HeaderGridLinesVisibility` property. `GridLinesVisibility`
affects body lines only; header lines are always drawn. To hide them,
override `TabularSurfaceHeaderSeparatorBrush` with `Transparent`.

### Current Behavior
- Headers are built in C++ with no template, no visual states and forced
local typography, so apps can't restyle them. Header separators don't
show.
- Header peers report `HeaderItem` without Transform, so UIA clients
can't resize columns.
- `SortByColumn` ignores `CanSort`; `CanSort=false` on a sorted column
leaves the sort in place; sorting through a source another table owns
reports success; some implicit clears raise `Sorted(None)` while the
app's sort remains.
- The cell peer constructor accepts invalid arguments; a throw in
`BeginEdit` leaves edit state half-open.
- Recycling a row rebuilt every cell, refreshed chrome up to twice and
invalidated the table's measure.
- The outer border has no dedicated brush; the default group header uses
raw weights and off-grid spacing.

### New Behavior
- Headers use the templated `TableViewColumnHeader` (see API above);
typography, padding and brushes come from Style setters.
- Header peers implement `ITransformProvider` through the existing
resize path (Min/Max clamping, scale conversion; pinned columns report
`CanResize=false`).
- `CanSort=false` blocks header clicks, `SortByColumn` (except `None`)
and `ToggleSortDirection`, and clears the column's own active sort;
sorts through a source owned by another table return false; `Sorted` is
raised only when the table's sort state changes.
- Cell peer constructor throws `E_INVALIDARG` on bad input; `BeginEdit`
rolls back on failure.
- Recycled rows reuse their cells unless cell automation peers exist;
chrome refreshes once.

> **Visible changes**
> - Outer border uses `CardStrokeColorDefault`.
> - Header lines are always shown, even when `GridLinesVisibility` is
`None` or `Horizontal`.
> - Group header restyled: 8px spacing; the count follows the header
`Foreground`.
> - Disabled header text and sort glyph dim.
> - TableView samples no longer opt out of High Contrast backplates
app-wide.

## Customer Impact

Restylable column headers, visible header separators, Fluent-aligned
outer border and group headers, UIA column resize for assistive
technology, smoother scrolling and predictable sort events.

## Regression Potential

- [ ] Low risk — isolated change, limited scope
- [x] Medium risk — touches shared components or public APIs
- [ ] High risk — architectural or breaking API change

Header construction (focus restore, frozen columns, UIA peer, tooltips,
resize, sort glyph) moved to a templated control. Sort event semantics
are tighter: `CanSort` is enforced on programmatic sorts and fewer
`Sorted` events fire. Outer border color and always-on header lines
change visibly. Covered by new and existing tests.

## How Has This Been Tested?

- [x] I have performed a self-review of my own code
- [x] I have added tests to cover my changes
- [x] Existing tests pass locally

Full TableView API and interaction suites on test VMs: 877/882 pass at
224d10d5c; 3 Localization tests are [Ignore] and 2 intermittent failures
passed 3/3 on rerun. Product, test apps and TableView sample apps build
(x64 chk).

Also covered:
`VerifyDisabledGroupHeaderCountFollowsContentTemplateChanges`.

Key new tests:
- `VerifyColumnHeaderTemplateParts`, `VerifyColumnHeaderSortStates`,
`VerifyColumnHeaderTypographyHasNoLocalValues`
- `VerifyColumnHeaderStyleApplies`,
`VerifyBasedOnOnlyColumnHeaderStyleApplies`,
`VerifyIncompatibleColumnHeaderStyleIsIgnored`
- `VerifyHeaderGridLinesShowWhateverTheBodyGridLines`,
`VerifyTransparentHeaderSeparatorBrushHidesHeaderLines`,
`VerifyGridLineAndOuterBorderBrushesMatchFluentStrokeTokens`
- `VerifyDisablingHighContrastHoveredHeaderKeepsDisabledForeground`,
`VerifyDefaultGroupHeaderCountInheritsForegroundThatFollowsStates`
- `VerifyTransformResizeAccountsForAncestorScale`,
`VerifyTransformResizeSmallWidthChangeWritesOnce`,
`VerifyHeaderDisabledByStyleIsNotEnabledOrInvokable`
- `VerifySortByColumnRespectsCanSort`,
`VerifyImplicitClearKeepsSourceSort`,
`VerifyUngatingKeepsAppLitColumnWithoutEvents`,
`VerifySortOptOutDuringBeginningEditKeepsTheEditOpen`
- `VerifyRecycledRowWithoutCellPeersReusesItsCells`,
`VerifyHeaderFocusStaysInHeaderBandWhenColumnsReplaced`,
`VerifyBeginEditThatThrowsRollsBackAndAllowsALaterEdit`,
`VerifyCellPeerConstructorValidatesArguments`

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 94961bb8-d187-483c-bece-19e203752c67
2026-10-23 14:10:17 +05:30

533 lines
15 KiB
C++

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#include "pch.h"
#include "common.h"
#include "TableView.h"
#include "TableViewCellsPanel.h"
#include "TableViewAutomationHelpers.h"
#include "TableViewColumnHeaderAutomationPeer.h"
#include "TableViewColumnHeader.h"
#include "TableViewToolTipHelpers.h"
#include "TableViewColumnHeaderAutomationPeer.properties.cpp"
#include "ResourceAccessor.h"
#include "Utils.h"
#include <UIAutomationCore.h>
#include <UIAutomationCoreApi.h>
#include <cmath>
#include <cwctype>
#include <limits>
#include <string_view>
namespace
{
uint32_t AutomationIdentityForColumn(winrt::TableViewColumn const& column)
{
return column ? winrt::get_self<TableViewColumn>(column)->AutomationIdentity() : 0;
}
winrt::TableView OwnerForPublicConstructor(winrt::TableView const& table, winrt::TableViewColumn const& column)
{
if (table && column &&
winrt::get_self<TableViewColumn>(column)->GetOwningTableView() == table)
{
return table;
}
throw winrt::hresult_invalid_argument();
}
}
TableViewColumnHeaderAutomationPeer::TableViewColumnHeaderAutomationPeer(
winrt::TableView const& owner,
winrt::TableViewColumn const& column)
: ReferenceTracker(OwnerForPublicConstructor(owner, column))
, m_column(winrt::make_weak(column))
, m_table(winrt::make_weak(owner))
, m_columnAutomationIdentity(AutomationIdentityForColumn(column))
{
}
TableViewColumnHeaderAutomationPeer::TableViewColumnHeaderAutomationPeer(
winrt::FrameworkElement const& header,
winrt::TableView const& table,
winrt::TableViewColumn const& column)
: ReferenceTracker(header)
, m_column(winrt::make_weak(column))
, m_table(winrt::make_weak(table))
, m_columnAutomationIdentity(AutomationIdentityForColumn(column))
{
}
hstring TableViewColumnHeaderAutomationPeer::GetClassNameCore()
{
return L"TableViewColumnHeader";
}
hstring TableViewColumnHeaderAutomationPeer::GetNameCore()
{
if (auto const headerElement = GetHeaderElement())
{
if (auto const name = winrt::AutomationProperties::GetName(headerElement); !name.empty())
{
return name;
}
if (auto const label = GetLabeledBy())
{
if (auto const name = label.GetName(); !name.empty())
{
return name;
}
}
}
if (auto const headerString = TableViewDetails::TryGetColumnHeaderText(m_column.get()))
{
return *headerString;
}
// Only the content region names the header, never the grid line, glyph or gripper.
if (auto const header = GetHeaderElement().try_as<winrt::TableViewColumnHeader>())
{
uint32_t remaining = 64;
if (auto const name = GetCellContentName(
winrt::get_self<TableViewColumnHeader>(header)->GetContentPresenterInternal(), true, 8, remaining);
!name.empty())
{
return name;
}
}
return {};
}
winrt::AutomationControlType TableViewColumnHeaderAutomationPeer::GetAutomationControlTypeCore()
{
return winrt::AutomationControlType::HeaderItem;
}
hstring TableViewColumnHeaderAutomationPeer::GetAutomationIdCore()
{
// An author-supplied id on the realized header always wins.
if (auto const headerElement = GetHeaderElement())
{
if (auto const automationId = winrt::AutomationProperties::GetAutomationId(headerElement);
!automationId.empty())
{
return automationId;
}
}
std::wstring automationId{ L"TableViewColumnHeader_" };
automationId.append(std::to_wstring(m_columnAutomationIdentity));
return hstring{ automationId };
}
hstring TableViewColumnHeaderAutomationPeer::GetHelpTextCore()
{
auto const column = m_column.get();
if (!column)
{
return __super::GetHelpTextCore();
}
// Only a column the control will actually sort reports a sort state; on any other column the
// absence of a sort state is the honest answer.
winrt::hstring sortText{};
if (IsSortableColumn())
{
switch (column.SortDirection())
{
case winrt::SortDirection::Ascending:
sortText = TryGetLocalizedString(SR_TableViewSortAscendingHelpText);
break;
case winrt::SortDirection::Descending:
sortText = TryGetLocalizedString(SR_TableViewSortDescendingHelpText);
break;
case winrt::SortDirection::None:
default:
sortText = TryGetLocalizedString(SR_TableViewSortNoneHelpText);
break;
}
}
// From the column, not the realized header: the peer can be queried before the band exists.
// String only; rich content is mouse-only, as with cells.
winrt::hstring toolTipText{};
if (auto const text = TableViewDetails::TryGetString(column.HeaderToolTip()))
{
toolTipText = *text;
}
// Dropped when it repeats the header name, to avoid a double announcement.
if (!toolTipText.empty() && toolTipText == GetNameCore())
{
toolTipText = {};
}
if (toolTipText.empty())
{
return sortText.empty() ? __super::GetHelpTextCore() : sortText;
}
if (sortText.empty())
{
return toolTipText;
}
// A sighted user gets both at a glance, so neither is dropped.
auto const format = TryGetLocalizedString(SR_TableViewColumnHeaderHelpTextFormat);
if (format.empty())
{
return toolTipText;
}
// The format supplies its own separator; a tooltip written as a sentence would otherwise read "..".
std::wstring_view trimmedToolTip{ toolTipText };
while (!trimmedToolTip.empty() &&
(trimmedToolTip.back() == L'.' || trimmedToolTip.back() == L'\u3002' || std::iswspace(trimmedToolTip.back())))
{
trimmedToolTip.remove_suffix(1);
}
if (trimmedToolTip.empty())
{
return sortText;
}
return StringUtil::FormatString(format, std::wstring{ trimmedToolTip }.c_str(), sortText.c_str());
}
winrt::IInspectable TableViewColumnHeaderAutomationPeer::GetPatternCore(winrt::PatternInterface patternInterface)
{
if (patternInterface == winrt::PatternInterface::Invoke && IsSortableColumn())
{
return *this;
}
if (patternInterface == winrt::PatternInterface::Transform && IsResizableColumn())
{
return *this;
}
return __super::GetPatternCore(patternInterface);
}
bool TableViewColumnHeaderAutomationPeer::IsEnabledCore()
{
auto const table = m_table.get();
if (!table || !table.IsEnabled())
{
return false;
}
// The header's own state, and that of any template control around it (for example the header
// ScrollViewer), can be disabled independently of the table.
auto const header = GetHeaderElement();
if (auto const headerControl = header.try_as<winrt::Control>(); headerControl && !headerControl.IsEnabled())
{
return false;
}
auto ancestor = winrt::VisualTreeHelper::GetParent(header ? header : Owner());
while (ancestor && ancestor != table)
{
if (auto const control = ancestor.try_as<winrt::Control>(); control && !control.IsEnabled())
{
return false;
}
ancestor = winrt::VisualTreeHelper::GetParent(ancestor);
}
return true;
}
void TableViewColumnHeaderAutomationPeer::Invoke()
{
if (!IsEnabled())
{
throw winrt::hresult_error(UIA_E_ELEMENTNOTENABLED);
}
if (!IsSortableColumn())
{
throw winrt::hresult_error(UIA_E_INVALIDOPERATION);
}
if (auto const column = m_column.get())
{
if (auto const owner = m_table.get())
{
winrt::get_self<TableView>(owner)->ToggleSortDirection(column);
return;
}
}
throw winrt::hresult_error(UIA_E_ELEMENTNOTAVAILABLE);
}
bool TableViewColumnHeaderAutomationPeer::CanMove()
{
return false;
}
bool TableViewColumnHeaderAutomationPeer::CanResize()
{
if (!IsResizableColumn())
{
return false;
}
auto const owner = m_table.get();
return owner && winrt::get_self<TableView>(owner)->CanResizeColumnFromAutomation(m_column.get());
}
bool TableViewColumnHeaderAutomationPeer::CanRotate()
{
return false;
}
void TableViewColumnHeaderAutomationPeer::Move(double, double)
{
throw winrt::hresult_error(UIA_E_INVALIDOPERATION);
}
void TableViewColumnHeaderAutomationPeer::Resize(double width, double)
{
if (!IsEnabled())
{
throw winrt::hresult_error(UIA_E_ELEMENTNOTENABLED);
}
if (!std::isfinite(width) || width < 0.0)
{
throw winrt::hresult_invalid_argument();
}
if (!CanResize())
{
throw winrt::hresult_error(UIA_E_INVALIDOPERATION);
}
// Height is ignored: a column header only resizes along the column axis.
auto const column = m_column.get();
auto const owner = m_table.get();
if (!column || !owner)
{
throw winrt::hresult_error(UIA_E_ELEMENTNOTAVAILABLE);
}
// UIA sizes are physical pixels, like BoundingRectangle; column widths are DIPs in the table's
// own frame, below any scale applied above it.
if (auto const xamlRoot = owner.XamlRoot())
{
double scale = xamlRoot.RasterizationScale();
try
{
const auto unit = owner.TransformToVisual(nullptr).TransformBounds({ 0.0f, 0.0f, 1.0f, 0.0f });
if (unit.Width > 0.0f)
{
scale *= unit.Width;
}
}
catch (...)
{
// Not in the live tree; the display scale alone is the best answer.
}
if (scale > 0.0)
{
width /= scale;
}
}
if (!winrt::get_self<TableView>(owner)->TryResizeColumnFromAutomation(column, width))
{
throw winrt::hresult_error(UIA_E_INVALIDOPERATION);
}
}
void TableViewColumnHeaderAutomationPeer::Rotate(double)
{
throw winrt::hresult_error(UIA_E_INVALIDOPERATION);
}
winrt::Windows::Foundation::Collections::IVector<winrt::AutomationPeer> TableViewColumnHeaderAutomationPeer::GetChildrenCore()
{
if (!IsTableViewOwned())
{
return __super::GetChildrenCore();
}
return winrt::single_threaded_vector<winrt::AutomationPeer>();
}
winrt::Windows::Foundation::Rect TableViewColumnHeaderAutomationPeer::GetBoundingRectangleCore()
{
if (IsTableViewOwned())
{
return {};
}
return __super::GetBoundingRectangleCore();
}
winrt::Windows::Foundation::Point TableViewColumnHeaderAutomationPeer::GetClickablePointCore()
{
if (IsTableViewOwned())
{
return { std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN() };
}
return __super::GetClickablePointCore();
}
bool TableViewColumnHeaderAutomationPeer::IsOffscreenCore()
{
return IsTableViewOwned() ? true : __super::IsOffscreenCore();
}
void TableViewColumnHeaderAutomationPeer::ShowContextMenuCore()
{
if (!IsTableViewOwned())
{
__super::ShowContextMenuCore();
return;
}
auto const column = m_column.get();
if (!column || !IsVisibleColumn(column))
{
return;
}
if (auto const header = GetHeaderElement())
{
if (auto const peer = winrt::FrameworkElementAutomationPeer::CreatePeerForElement(header))
{
peer.ShowContextMenu();
}
}
}
bool TableViewColumnHeaderAutomationPeer::IsTableViewOwned()
{
return Owner().try_as<winrt::TableView>() != nullptr;
}
bool TableViewColumnHeaderAutomationPeer::IsSortableColumn()
{
auto const column = m_column.get();
if (!column || !column.CanSort() || !IsVisibleColumn(column))
{
return false;
}
auto const owner = m_table.get();
return owner && owner.IsLoaded() && owner.CanUserSortColumns();
}
// The static opt-in only; whether the gripper is usable right now is CanResize's job.
bool TableViewColumnHeaderAutomationPeer::IsResizableColumn()
{
auto const column = m_column.get();
if (!column || !column.CanResize() || !IsVisibleColumn(column))
{
return false;
}
auto const owner = m_table.get();
return owner && owner.CanUserResizeColumns();
}
int32_t TableViewColumnHeaderAutomationPeer::GetPositionInSetCore()
{
// The header's attached override wins over the visible-column position.
if (auto const header = GetHeaderElement())
{
if (const auto provided = winrt::AutomationProperties::GetPositionInSet(header); provided > 0)
{
return provided;
}
}
const auto index = GetColumnIndex();
// 0 is UIA's "not specified"; valid values are 1-based, so -1 reached the client as a nonsense
// position.
return index >= 0 ? index + 1 : 0;
}
int32_t TableViewColumnHeaderAutomationPeer::GetSizeOfSetCore()
{
if (auto const header = GetHeaderElement())
{
if (const auto provided = winrt::AutomationProperties::GetSizeOfSet(header); provided > 0)
{
return provided;
}
}
// Total visible column count, so PositionInSet reads as "i of n".
if (auto const owner = m_table.get())
{
if (auto const columns = owner.Columns())
{
int32_t count = 0;
for (auto const& col : columns)
{
if (IsVisibleColumn(col)) { ++count; }
}
if (count > 0) { return count; }
}
}
return 0;
}
int32_t TableViewColumnHeaderAutomationPeer::GetColumnIndex()
{
// Logical visible column index, matching GetSizeOfSetCore's visible basis
// and the rendered header order, so PositionInSet ("i") and SizeOfSet ("n") stay
// consistent even when Columns contains null holes or collapsed columns.
// Columns are matched by identity; a column instance is a single logical position
// (single-owner model), so the same instance appearing twice in Columns is unsupported.
if (auto const owner = m_table.get())
{
if (auto const col = m_column.get())
{
if (!IsVisibleColumn(col))
{
return -1;
}
if (auto const columns = owner.Columns())
{
int32_t logicalIndex = 0;
for (auto const& c : columns)
{
if (c == col) { return logicalIndex; }
if (IsVisibleColumn(c)) { ++logicalIndex; }
}
}
}
}
return -1;
}
winrt::FrameworkElement TableViewColumnHeaderAutomationPeer::GetHeaderElement()
{
// Match by Tag so null Columns entries do not skew logical indexes.
auto const owner = m_table.get();
auto const col = m_column.get();
if (!owner || !col)
{
return nullptr;
}
auto const host = winrt::get_self<TableView>(owner)->GetHeaderHostInternal();
if (!host)
{
return nullptr;
}
auto const header = TableViewCellsPanel::CellForColumn(host, col);
if (!Owner().try_as<winrt::TableView>() && header != Owner())
{
return nullptr;
}
return header;
}