using System;
using Avalonia;
using Avalonia.Controls;
using NewLife.XCoder.Services;
namespace NewLife.XCoder.Shell;
/// <summary>浮动工具窗口:承载与标签相同的工具实例</summary>
public partial class FloatingToolWindow : Window
{
private readonly Action? _onReturn;
private String? _key;
/// <summary>实例化(供 XAML 设计器使用)</summary>
public FloatingToolWindow() => InitializeComponent();
/// <summary>按工具创建浮动窗口</summary>
/// <param name="tool">工具描述</param>
/// <param name="view">工具内容视图</param>
/// <param name="onReturn">移回标签时的回调</param>
public FloatingToolWindow(ToolDescriptor tool, Control view, Action onReturn) : this()
{
_onReturn = onReturn;
_key = tool.Key;
Title = tool.DisplayTitle + " · " + LocalizationService.T("Floating Window");
TitleText.Text = tool.Icon + " " + tool.DisplayTitle;
Host.Content = view;
LocalizationService.Changed += OnLanguageChanged;
PinBox.IsCheckedChanged += (_, _) => Topmost = PinBox.IsChecked == true;
// 默认置顶取自外壳偏好,用户仍可用图钉随时切换
var onTop = ShellPreferenceStore.Load().FloatOnTop;
PinBox.IsChecked = onTop;
Topmost = onTop;
ReturnButton.Click += (_, _) =>
{
Host.Content = null;
_onReturn?.Invoke();
Close();
};
RestoreGeometry();
Closed += (_, _) =>
{
SaveGeometry();
LocalizationService.Changed -= OnLanguageChanged;
};
}
private void OnLanguageChanged(String language)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Post(() => OnLanguageChanged(language));
return;
}
var tool = ToolRegistry.Find(_key ?? "");
if (tool == null) return;
Title = tool.DisplayTitle + " · " + LocalizationService.T("Floating Window");
TitleText.Text = tool.Icon + " " + tool.DisplayTitle;
}
/// <summary>工具内容宿主</summary>
public ContentControl HostControl => Host;
private void RestoreGeometry()
{
var geometry = UiLayoutStore.Load(_key ?? "");
if (geometry == null) return;
WindowStartupLocation = WindowStartupLocation.Manual;
Width = geometry.Width;
Height = geometry.Height;
Position = new PixelPoint(geometry.X, geometry.Y);
}
private void SaveGeometry()
{
if (String.IsNullOrEmpty(_key)) return;
if (WindowState != WindowState.Normal) return;
var width = (Int32)Math.Round(Bounds.Width);
var height = (Int32)Math.Round(Bounds.Height);
if (width <= 0 || height <= 0) return;
UiLayoutStore.Save(_key!, new WindowGeometry(Position.X, Position.Y, width, height));
}
}
|