Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions components/Segmented/src/ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ This package contains the following controls in the `CommunityToolkit.WinUI.Cont

- Segmented

On Windows, `Segmented` exposes the UI Automation Selection pattern and its items
expose the SelectionItem pattern through native list automation peers. Set
`AutomationProperties.Name` on the control to provide an accessible name.

## Which Package is for me?

If you're developing with _UWP/WinUI 2 or Uno.UI_ you should be using the `CommunityToolkit.Uwp.Controls.Segmented` package.
Expand Down
4 changes: 4 additions & 0 deletions components/Segmented/src/Segmented/Segmented.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using CommunityToolkit.WinUI.Automation.Peers;
using Windows.System;

namespace CommunityToolkit.WinUI.Controls;
Expand All @@ -24,6 +25,9 @@ public Segmented()
RegisterPropertyChangedCallback(SelectedIndexProperty, OnSelectedIndexChanged);
}

/// <inheritdoc/>
protected override AutomationPeer OnCreateAutomationPeer() => new SegmentedAutomationPeer(this);

/// <inheritdoc/>
protected override DependencyObject GetContainerForItemOverride() => new SegmentedItem();

Expand Down
29 changes: 29 additions & 0 deletions components/Segmented/src/Segmented/SegmentedAutomationPeer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using CommunityToolkit.WinUI.Controls;

namespace CommunityToolkit.WinUI.Automation.Peers;

/// <summary>
/// Defines an automation peer for the <see cref="Segmented"/> control.
/// </summary>
public partial class SegmentedAutomationPeer : ListViewBaseAutomationPeer
{
/// <summary>
/// Initializes a new instance of the <see cref="SegmentedAutomationPeer"/> class.
/// </summary>
/// <param name="owner">The <see cref="Segmented"/> associated with this automation peer.</param>
public SegmentedAutomationPeer(Segmented owner)
: base(owner)
{
}

/// <inheritdoc/>
protected override string GetClassNameCore() => nameof(Segmented);

/// <inheritdoc/>
protected override ItemAutomationPeer OnCreateItemAutomationPeer(object item)
=> new ListViewItemDataAutomationPeer(item, this);
}
1 change: 1 addition & 0 deletions components/Segmented/tests/Segmented.Tests.projitems
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<Import_RootNamespace>SegmentedTests</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Test_Segmented_AutomationPeer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ExampleSegmentedTestClass.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ExampleSegmentedTestPage.xaml.cs">
<DependentUpon>ExampleSegmentedTestPage.xaml</DependentUpon>
Expand Down
213 changes: 213 additions & 0 deletions components/Segmented/tests/Test_Segmented_AutomationPeer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#if !HAS_UNO
using CommunityToolkit.Tests;
using CommunityToolkit.Tooling.TestGen;
using CommunityToolkit.WinUI.Controls;
using System.Runtime.InteropServices;

#if WINAPPSDK
using Microsoft.UI.Xaml.Automation.Provider;
#else
using Windows.UI.Xaml.Automation.Provider;
#endif

namespace SegmentedTests;

[TestClass]
[TestCategory("Test_Segmented_AutomationPeer")]
public partial class Test_Segmented_AutomationPeer : VisualUITestBase
{
[UIThreadTestMethod]
public Task StringItemsExposeSelection() => VerifySelectionAsync(false);

[UIThreadTestMethod]
public Task ExplicitContainersExposeSelection() => VerifySelectionAsync(true);

[UIThreadTestMethod]
public Task StringItemSelectionRespectsIsEnabled() => VerifySelectAsync(false);

[UIThreadTestMethod]
public Task ExplicitContainerSelectionRespectsIsEnabled() => VerifySelectAsync(true);

[UIThreadTestMethod]
public Task StringItemPeersTrackCollectionChanges() => VerifyCollectionChangesAsync(false);

[UIThreadTestMethod]
public Task ExplicitContainerPeersTrackCollectionChanges() => VerifyCollectionChangesAsync(true);

private async Task VerifySelectionAsync(bool explicitContainers)
{
var (control, items) = CreateControl(explicitContainers);
await LoadTestContentAsync(control);

var peer = GetPeer(control);
Assert.AreEqual("View mode", peer.GetName());
Assert.AreEqual(nameof(Segmented), peer.GetClassName());
Assert.AreEqual(AutomationControlType.List, peer.GetAutomationControlType());

var selection = GetSelectionProvider(peer);
Assert.IsFalse(selection.CanSelectMultiple);

var itemProviders = GetItemProviders(peer, "List", "Grid", "Details");
for (var selectedIndex = 0; selectedIndex <= 1; selectedIndex++)
{
control.SelectedIndex = selectedIndex;

Assert.AreSame(items[selectedIndex], control.SelectedItem);
AssertSelection(selection, itemProviders, selectedIndex, selectedIndex == 0 ? "List" : "Grid");
}
}

private async Task VerifySelectAsync(bool explicitContainers)
{
var (control, items) = CreateControl(explicitContainers);
await LoadTestContentAsync(control);
control.SelectedIndex = 0;

var peer = GetPeer(control);
var selection = GetSelectionProvider(peer);
var itemProviders = GetItemProviders(peer, "List", "Grid", "Details");

itemProviders[1].Select();

Assert.AreEqual(1, control.SelectedIndex);
Assert.AreSame(items[1], control.SelectedItem);
AssertSelection(selection, itemProviders, 1, "Grid");

control.IsEnabled = false;
var exception = Assert.ThrowsException<COMException>(() => itemProviders[0].Select());
Assert.AreEqual(unchecked((int)0x80040200), exception.HResult, "Expected UIA_E_ELEMENTNOTENABLED.");

Assert.AreEqual(1, control.SelectedIndex);
Assert.AreSame(items[1], control.SelectedItem);

// Native item peers also reject IsSelected while disabled.
control.IsEnabled = true;
AssertSelection(selection, itemProviders, 1, "Grid");
}

private async Task VerifyCollectionChangesAsync(bool explicitContainers)
{
var (control, items) = CreateControl(explicitContainers);
await LoadTestContentAsync(control);
control.SelectedIndex = 1;

var peer = GetPeer(control);
var selection = GetSelectionProvider(peer);
var originalProviders = GetItemProviders(peer, "List", "Grid", "Details");
var selectedItem = items[1];

// Native Move notifications can reset selection; remove/insert preserves the selected logical item.
var movedItem = items[2];
items.RemoveAt(2);
items.Insert(0, movedItem);
await CompositionTargetHelper.ExecuteAfterCompositionRenderingAsync(() => { });

Assert.AreEqual(2, control.SelectedIndex);
Assert.AreSame(selectedItem, control.SelectedItem);
AssertSelection(selection, GetItemProviders(peer, "Details", "List", "Grid"), 2, "Grid");
AssertSelection(selection, originalProviders, 1, "Grid");

items.Remove(selectedItem);
await CompositionTargetHelper.ExecuteAfterCompositionRenderingAsync(() => { });

// A retained peer must still refer to List, not the item now at its old index.
originalProviders[0].Select();

Assert.AreEqual(1, control.SelectedIndex);
Assert.AreSame(items[1], control.SelectedItem);
AssertSelection(selection, GetItemProviders(peer, "Details", "List"), 1, "List");
AssertSelection(selection, new[] { originalProviders[0], originalProviders[2] }, 0, "List");
}

private static (Segmented Control, ObservableCollection<object> Items) CreateControl(bool explicitContainers)
{
var items = new ObservableCollection<object>();
foreach (var name in new[] { "List", "Grid", "Details" })
{
if (explicitContainers)
{
var item = new SegmentedItem { Content = name };
AutomationProperties.SetName(item, name);
items.Add(item);
}
else
{
items.Add(name);
}
}

var control = new Segmented
{
Name = "ViewModeControl",
ItemsSource = items,
SelectionMode = ListViewSelectionMode.Single,
};
AutomationProperties.SetName(control, "View mode");
return (control, items);
}

private static AutomationPeer GetPeer(Segmented control)
{
var peer = FrameworkElementAutomationPeer.CreatePeerForElement(control);
Assert.IsNotNull(peer);
return peer;
}

private static ISelectionProvider GetSelectionProvider(AutomationPeer peer)
{
var selection = peer.GetPattern(PatternInterface.Selection) as ISelectionProvider;
Assert.IsNotNull(selection, "The root must expose the native Selection provider.");
return selection;
}

private static ISelectionItemProvider[] GetItemProviders(AutomationPeer peer, params string[] expectedNames)
{
var children = peer.GetChildren();
Assert.IsNotNull(children);
Assert.AreEqual(expectedNames.Length, children.Count);

var providers = new ISelectionItemProvider[children.Count];
for (var index = 0; index < children.Count; index++)
{
Assert.AreEqual(expectedNames[index], children[index].GetName());
var provider = children[index].GetPattern(PatternInterface.SelectionItem) as ISelectionItemProvider;
Assert.IsNotNull(provider, $"{expectedNames[index]} must expose the native SelectionItem provider.");
Assert.IsNotNull(provider.SelectionContainer);
providers[index] = provider;
}

return providers;
}

private static void AssertSelection(ISelectionProvider selection, ISelectionItemProvider[] items, int selectedIndex, string expectedSelectedName)
{
var selectedItems = selection.GetSelection();
Assert.IsNotNull(selectedItems);
Assert.AreEqual(1, selectedItems.Length);
Comment thread
azchohfi marked this conversation as resolved.
Resolved

var selectedPeer = new ProviderPeerAccess().Resolve(selectedItems[0]);
Assert.IsNotNull(selectedPeer);
Assert.AreEqual(expectedSelectedName, selectedPeer.GetName(), "The root must return the selected item's provider.");

for (var index = 0; index < items.Length; index++)
{
Assert.AreEqual(index == selectedIndex, items[index].IsSelected, $"Selection identity at item {index}.");
}
}

// Exposes the protected conversion on a detached element, without replacing any control or item peer.
private sealed partial class ProviderPeerAccess : FrameworkElementAutomationPeer
{
public ProviderPeerAccess()
: base(new Grid())
{
}

public AutomationPeer Resolve(IRawElementProviderSimple provider) => PeerFromProvider(provider);
}
}
#endif
Loading