封装avalonia指定组件允许拖动的工具类
封装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
封装avalonia指定组件允许拖动的工具类的更多相关文章
- Android基于Retrofit2.0 +RxJava 封装的超好用的RetrofitClient工具类(六)
csdn :码小白 原文地址: http://blog.csdn.net/sk719887916/article/details/51958010 RetrofitClient 基于Retrofit2 ...
- 基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil
基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil,把日常能用到的各种CRUD都进行了简化封装,让普通程序员只需关注业务即可,因为非常简单,故直接贴源代码,大家若需使用可以直 ...
- 封装各种生成唯一性ID算法的工具类
/** * Copyright (c) 2005-2012 springside.org.cn * * Licensed under the Apache License, Version 2.0 ( ...
- 仿照hibernate封装的一个对数据库操作的jdbc工具类
package project02_Order_management.util; import java.io.IOException; import java.lang.reflect.Field; ...
- swift项目第十天:网络请求工具类的封装
import UIKit /* 必须先导入头文件:import AFNetworking */ import AFNetworking //MARK:-0:定义枚举:以枚举定义请求网络的get和pos ...
- 利用Jackson封装常用JsonUtil工具类
在日常的项目开发中,接口与接口之间.前后端之间的数据传输一般都是使用JSON格式,那必然会封装一些常用的Json数据转化的工具类,本文讲解下如何利用Jackson封装高复用性的Json转换工具类. 转 ...
- Apache Commons 工具类介绍及简单使用
转自:http://www.cnblogs.com/younggun/p/3247261.html Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动.下 ...
- Apache Commons 工具类简单使用
Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动.下面是我这几年做开发过程中自己用过的工具类做简单介绍. 组件 功能介绍 BeanUtils 提供了对于 ...
- RedisUtil工具类
转载:http://blog.csdn.net/liuxiao723846/article/details/50401406 1.使用了jedis客户端,对redis进行了封装,包括: 1)使用了re ...
- FileUtils删除文件的工具类
前提是知道文件在哪个文件夹下面然后到文件夹下面删除文件,如果文件夹也需要传参数需要对下面方法进行改造. ( 需要借助于commons-io.jar和ResourceUtils.java ) 1.De ...
随机推荐
- 5V升压8.4V,5V转8.4芯片电路图
PW5300是电流模式升压DC-DC转换器.其内置0.2Ω功率MOSFET的PWM电路使该稳压器具有效高的功率效率.内部补偿网络还可以程度地减少了6个外部元件的数量.误差放大器的同相输入接到0.6V精 ...
- Codeforces Round #838 (Div. 2) D. GCD Queries
题意 有个长度为n的排列p,[0,1,2,...n-1],你可以进行至多2*n次询问,每次询问两个i,j,返回gcd(pi,pj),让你在规定时间内猜出0在哪两个位置之一 思路 这是一道交互题,询问的 ...
- java中方法传参形式
成员方法传参形式: 1.基本数据类型:传递的是值 public class Object03 { public static void main(String[] args) { AA aa = ne ...
- 从面试题入手,畅谈 Vue 3 性能优化
前言 今年又是一个非常寒冷的冬天,很多公司都开始人员精简.市场从来不缺前端,但对高级前端的需求还是特别强烈的.一些大厂的面试官为了区分候选人对前端领域能力的深度,经常会在面试过程中考察一些前端框架的源 ...
- 痞子衡嵌入式:对比恩智浦全系列MCU(包含Kinetis/LPC/i.MXRT/MCX)的GPIO电平中断设计差异
大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是恩智浦全系列MCU(包含Kinetis, LPC, i.MXRT, MCX)的GPIO电平中断设计差异. 在痞子衡旧文 <以i.M ...
- Service层和Dao层的一些自我理解(╥╯^╰╥)(╥╯^╰╥)(学了这么久,这玩意儿似懂非懂的)
学习java已经有很长时间了,但由于是在学校学的,基础不怎么扎实. 这几个月系统的学习,弥补了很多的缺陷,虽然大多数时间都在弄算法(咳咳),我前面的博客有写 如果有认真看过我代码的朋友会发现,我其实英 ...
- APIO2022 游记
Day 0 有人刚登记完房间就把房卡落在房间里了我不说是谁(真不是我,不信去问jth) 下午把gen把模拟赛的题补了一下,T3是个不太可做的虚树上淀粉质dp,先咕着. Day 1 上午来的比较晚,没有 ...
- CF896E Welcome home, Chtholly
题面 维护一个\(n(n\leqslant 100000)\)个元素序列\(a_1,a_2,\dots,a_n\),有\(m(m\leqslant 100000)\)次操作,分为如下两种. 给定\(l ...
- Matplotlib 绘制折线图
Matplotlib matplotlib: 最流行的Python底层绘图库,主要做数据可视化图表,名字取材于MATLAB,模仿MATLAB构建 绘制折线图 绘制两小时的温度变化 from matpl ...
- react,vue中的key有什么作用?(key的内部原理)
1.虚拟DOM中的key的作用: key是虚拟dom对象的标识,当状态中的数据发生变化时,vue会根据新数据生成新的虚拟dom,随后vue进行新的虚拟dom与旧的虚拟dom的差异比较. 2.比较规则 ...