Files
Example/RazorEngineTest/MyControl.cs

138 lines
4.3 KiB
C#
Raw Permalink Normal View History

2025-09-06 22:55:02 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace RazorEngineTest
{
/// <summary>
/// 按照步骤 1a 或 1b 操作,然后执行步骤 2 以在 XAML 文件中使用此自定义控件。
///
/// 步骤 1a) 在当前项目中存在的 XAML 文件中使用该自定义控件。
/// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
/// 元素中:
///
/// xmlns:MyNamespace="clr-namespace:RazorEngineTest"
///
///
/// 步骤 1b) 在其他项目中存在的 XAML 文件中使用该自定义控件。
/// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
/// 元素中:
///
/// xmlns:MyNamespace="clr-namespace:RazorEngineTest;assembly=RazorEngineTest"
///
/// 您还需要添加一个从 XAML 文件所在的项目到此项目的项目引用,
/// 并重新生成以避免编译错误:
///
/// 在解决方案资源管理器中右击目标项目,然后依次单击
/// “添加引用”->“项目”->[浏览查找并选择此项目]
///
///
/// 步骤 2)
/// 继续操作并在 XAML 文件中使用控件。
///
/// <MyNamespace:MyControl/>
///
/// </summary>
public class MyControl : Control
{
private DropPlacementAdorner? _currentAdorner = null;
2025-09-06 22:55:02 +08:00
private AdornerLayer? _adornerLayer = null;
static MyControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
}
// 公开一个属性来获取当前拖放位置
public string CurrentDropPosition { get; private set; } = "";
private void UpdateAdorner(string position)
{
RemoveAdorner();
if (_adornerLayer != null)
{
_currentAdorner = new DropPlacementAdorner(this, position);
2025-09-06 22:55:02 +08:00
_adornerLayer.Add(_currentAdorner);
}
}
private void RemoveAdorner()
{
if (_currentAdorner != null && _adornerLayer != null)
{
_adornerLayer.Remove(_currentAdorner);
_currentAdorner = null;
}
}
protected override void OnMouseEnter(MouseEventArgs e)
{
base.OnMouseEnter(e);
// 初始化装饰器层
_adornerLayer = AdornerLayer.GetAdornerLayer(this);
e.Handled = true;
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
// 获取鼠标相对于当前控件的位置
Point position = e.GetPosition(this);
// 计算控件的大小
double width = ActualWidth;
double height = ActualHeight;
// 定义边缘阈值例如距离边缘10%的区域被认为是边缘)
double edgeThreshold = 0.25;
double horizontalThreshold = width * edgeThreshold;
double verticalThreshold = height * edgeThreshold;
// 判断位置
string positionName;
if (position.X < horizontalThreshold)
{
positionName = "左";
}
else if (position.X > width - horizontalThreshold)
{
positionName = "右";
}
else if (position.Y < verticalThreshold)
{
positionName = "上";
}
else if (position.Y > height - verticalThreshold)
{
positionName = "下";
}
else
{
positionName = "中";
}
// 更新当前位置属性
CurrentDropPosition = positionName;
// 更新装饰器
UpdateAdorner(positionName);
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
RemoveAdorner();
CurrentDropPosition = "";
}
}
}