Skip to content
This repository has been archived by the owner on Nov 1, 2024. It is now read-only.

Commit

Permalink
Add FocusSelectedItemBehavior
Browse files Browse the repository at this point in the history
  • Loading branch information
wieslawsoltes committed Apr 24, 2024
1 parent b11c391 commit dc236fb
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/Avalonia.Xaml.Interactions.Custom/FocusSelectedItemBehavior.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Reactive.Disposables;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Threading;

namespace Avalonia.Xaml.Interactions.Custom;

/// <summary>
///
/// </summary>
public class FocusSelectedItemBehavior : AttachedToVisualTreeBehavior<ItemsControl>
{
/// <summary>
///
/// </summary>
/// <param name="disposable"></param>
protected override void OnAttachedToVisualTree(CompositeDisposable disposable)
{
var dispose = AssociatedObject?
.GetObservable(SelectingItemsControl.SelectedItemProperty)
.Subscribe(selectedItem =>
{
var item = selectedItem;
if (item is not null)
{
Dispatcher.UIThread.Post(() =>
{
var container = AssociatedObject.ContainerFromItem(item);
if (container is not null)
{
container.Focus();
}
});
}
});

if (dispose is not null)
{
disposable.Add(dispose);
}
}
}

0 comments on commit dc236fb

Please sign in to comment.