封裝avalonia指定元件允許拖動的工具類
建立Avalonia
的MVVM專案,命名DragDemo
,然後將專案的Nuget包更新到預覽版
<ItemGroup>
<PackageReference Include="Avalonia" Version="11.0.0-preview5" />
<PackageReference Include="Avalonia.Desktop" Version="11.0.0-preview5" />
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.0.0-preview5" />
<PackageReference Include="Avalonia.ReactiveUI" Version="11.0.0-preview5" />
<PackageReference Include="XamlNameReferenceGenerator" Version="1.5.1" />
</ItemGroup>
更新完成以後ViewLocator
和App.axaml
會報錯,
修改ViewLocator.cs
為下面的程式碼
using System;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using DragDemo.ViewModels;
namespace DragDemo;
public class ViewLocator : IDataTemplate
{
/// <summary>
/// 將IControl修改成Control
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public Control Build(object data)
{
var name = data.GetType().FullName!.Replace("ViewModel", "View");
var type = Type.GetType(name);
if (type != null)
{
return (Control)Activator.CreateInstance(type)!;
}
return new TextBlock { Text = "Not Found: " + name };
}
public bool Match(object data)
{
return data is ViewModelBase;
}
}
新增Avalonia.Themes.Fluent
,因為預覽版本的包已經獨立需要單獨安裝
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.0.0-preview5" />
開啟App.axaml
檔案,修改為以下程式碼
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DragDemo"
RequestedThemeVariant="Light"
x:Class="DragDemo.App">
<Application.DataTemplates>
<local:ViewLocator/>
</Application.DataTemplates>
<Application.Styles>
<FluentTheme DensityStyle="Compact"/>
</Application.Styles>
</Application>
開啟Views/MainWindow.axaml
在頭部新增以下程式碼,讓視窗無邊框,設定指定視窗Height="38" Width="471",引數讓其不要佔用整個螢幕,
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:DragDemo.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="DragDemo.Views.MainWindow"
Icon="/Assets/avalonia-logo.ico"
ExtendClientAreaToDecorationsHint="True"
ExtendClientAreaChromeHints="NoChrome"
ExtendClientAreaTitleBarHeightHint="-1"
MaxHeight="38" MaxWidth="471"
Title="DragDemo">
<Window.Styles>
<Style Selector="Window">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Style>
</Window.Styles>
<Design.DataContext>
<vm:MainWindowViewModel/>
</Design.DataContext>
<StackPanel>
<StackPanel Opacity="0.1" Height="38" Width="471">
</StackPanel>
<Border Name="Border" Width="471" CornerRadius="10" Opacity="1" Background="#FFFFFF">
<Button>按鈕</Button>
</Border>
</StackPanel>
</Window>
以下程式碼在上面視窗用於設定視窗無邊框
<Window.Styles>
<Style Selector="Window">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Style>
</Window.Styles>
然後開啟/Views/MainWindow.axaml.cs
檔案,將邊框設定成無邊框,並且設定窗體透明為WindowTransparencyLevel.Transparent
using Avalonia;
using Avalonia.Controls;
namespace DragDemo.Views;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.TransparencyLevelHint = WindowTransparencyLevel.Transparent;
ExtendClientAreaToDecorationsHint = true;
WindowState = WindowState.Maximized;
}
}
效果圖如下,因為限制了窗體最大大小,並且在按鈕上面新增了透明區塊,這樣看起來就像是懸浮了
然後我們開始寫指定元件拖動工具類,建立DragControlHelper.cs
以下就是封裝的工具類 定義了一個ConcurrentDictionary
靜態引數,指定元件為Key
,Value
為DragModule
,DragModule
模型中定義了拖動的邏輯在呼叫StartDrag
的時候傳遞需要拖動的元件,他會建立一個DragModule
物件,建立的時候會建立定時器,當滑鼠被按下時啟動定時器,當滑鼠被釋放時定時器被停止,定時器用於平滑更新窗體移動,如果直接移動窗體會抖動。
using System;
using System.Collections.Concurrent;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace DragDemo;
public class DragControlHelper
{
private static ConcurrentDictionary<Control, DragModule> _dragModules = new();
public static void StartDrag(Control userControl)
{
_dragModules.TryAdd(userControl, new DragModule(userControl));
}
public static void StopDrag(Control userControl)
{
if (_dragModules.TryRemove(userControl, out var dragModule))
{
dragModule.Dispose();
}
}
}
class DragModule : IDisposable
{
/// <summary>
/// 記錄上一次滑鼠位置
/// </summary>
private Point? lastMousePosition;
/// <summary>
/// 用於平滑更新座標的計時器
/// </summary>
private DispatcherTimer _timer;
/// <summary>
/// 標記是否先啟動了拖動
/// </summary>
private bool isDragging = false;
/// <summary>
/// 需要更新的座標點
/// </summary>
private PixelPoint? _targetPosition;
public Control UserControl { get; set; }
public DragModule(Control userControl)
{
UserControl = userControl;
// 新增當前控制元件的事件監聽
UserControl.PointerPressed += OnPointerPressed;
UserControl.PointerMoved += OnPointerMoved;
UserControl.PointerReleased += OnPointerReleased;
// 初始化計時器
_timer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(10)
};
_timer.Tick += OnTimerTick;
}
/// <summary>
/// 計時器事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnTimerTick(object sender, EventArgs e)
{
var window = UserControl.FindAncestorOfType<Window>();
if (window != null && window.Position != _targetPosition)
{
// 更新座標
window.Position = (PixelPoint)_targetPosition;
}
}
private void OnPointerPressed(object sender, PointerPressedEventArgs e)
{
if (!e.GetCurrentPoint(UserControl).Properties.IsLeftButtonPressed) return;
// 啟動拖動
isDragging = true;
// 記錄當前座標
lastMousePosition = e.GetPosition(UserControl);
e.Handled = true;
// 啟動計時器
_timer.Start();
}
private void OnPointerReleased(object sender, PointerReleasedEventArgs e)
{
if (!isDragging) return;
// 停止拖動
isDragging = false;
e.Handled = true;
// 停止計時器
_timer.Stop();
}
private void OnPointerMoved(object sender, PointerEventArgs e)
{
if (!e.GetCurrentPoint(UserControl).Properties.IsLeftButtonPressed) return;
// 如果沒有啟動拖動,則不執行
if (!isDragging) return;
var currentMousePosition = e.GetPosition(UserControl);
var offset =currentMousePosition - lastMousePosition.Value;
var window = UserControl.FindAncestorOfType<Window>();
if (window != null)
{
// 記錄當前座標
_targetPosition = new PixelPoint(window.Position.X + (int)offset.X,
window.Position.Y + (int)offset.Y);
}
}
public void Dispose()
{
_timer.Stop();
_targetPosition = null;
lastMousePosition = null;
}
}
開啟MainWindow.axaml.cs
,修改成以下程式碼 ,在渲染成功以後拿到Border
(需要移動的元件),新增到DragControlHelper.StartDrag(border);
中,然後再OnUnloaded
的時候將Border
再解除安裝掉
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Threading;
namespace DragDemo.Views;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.TransparencyLevelHint = WindowTransparencyLevel.Transparent;
ExtendClientAreaToDecorationsHint = true;
WindowState = WindowState.Maximized;
}
public override void Render(DrawingContext context)
{
base.Render(context);
Dispatcher.UIThread.Post(() =>
{
var border = this.Find<Border>("Border");
DragControlHelper.StartDrag(border);
});
}
protected override void OnUnloaded()
{
var border = this.Find<Border>("Border");
DragControlHelper.StopDrag(border);
base.OnUnloaded();
}
}
效果展示:
來著token的分享
技術交流群:737776595