feat: add function to set selected item from outside and sync to UI.

This commit is contained in:
rabbitism
2024-02-14 11:40:19 +08:00
parent f67a5a313c
commit 122f89fc57
4 changed files with 133 additions and 12 deletions

View File

@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Reflection;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
@@ -164,7 +165,25 @@ public class NavMenu: ItemsControl
private void OnSelectedItemChange(AvaloniaPropertyChangedEventArgs<object?> args)
{
Debug.WriteLine(args.NewValue.Value);
if (_updateFromUI) return;
var newValue = args.NewValue.Value;
if (newValue is null)
{
ClearAll();
return;
}
var leaves = GetLeafMenus();
bool found = false;
foreach (var leaf in leaves)
{
if (leaf == newValue || leaf.DataContext == newValue)
{
leaf.SelectItem(leaf);
found = true;
}
}
if (found) return;
ClearAll();
}
protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
@@ -177,8 +196,11 @@ public class NavMenu: ItemsControl
return new NavMenuItem();
}
private bool _updateFromUI;
internal void SelectItem(NavMenuItem item, NavMenuItem parent)
{
_updateFromUI = true;
// if (item.IsSelected) return;
foreach (var child in LogicalChildren)
{
@@ -199,6 +221,34 @@ public class NavMenu: ItemsControl
{
SelectedItem = item;
}
item.IsSelected = true;
item.BringIntoView();
// item.IsSelected = true;
_updateFromUI = false;
}
private IEnumerable<NavMenuItem> GetLeafMenus()
{
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
var leafs = item.GetLeafMenus();
foreach (var leaf in leafs)
{
yield return leaf;
}
}
}
}
private void ClearAll()
{
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
item.ClearSelection();
}
}
}
}

View File

@@ -265,7 +265,7 @@ public class NavMenuItem: HeaderedSelectingItemsControl
e.Handled = true;
}
protected void SelectItem(NavMenuItem item)
internal void SelectItem(NavMenuItem item)
{
if (item == this)
{
@@ -329,4 +329,24 @@ public class NavMenuItem: HeaderedSelectingItemsControl
return logical != null ? result : @default;
}
internal IEnumerable<NavMenuItem> GetLeafMenus()
{
if (this.ItemCount == 0)
{
yield return this;
yield break;
}
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
var items = item.GetLeafMenus();
foreach (var i in items)
{
yield return i;
}
}
}
}
}