最近为了实现WPF中弹框组件写了一个小例子:
组件要求:
1.自定义标题
2自定义标题颜色
3提供关闭按钮,
4.弹框内容可由调用方自行嵌入
xaml代码
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1.Controls"
MouseLeftButtonDown="UserControl_MouseLeftButtonDown"
MouseLeftButtonUp="UserControl_MouseLeftButtonUp"
MouseMove="UserControl_MouseMove" Height="142" Width="112">
cs代码
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using WpfApp1.Models;
namespace WpfApp1.Controls
{
public partial class CustomPopup : UserControl
{
private bool isDragging;
private Point offset;
public CustomPopup()
{
InitializeComponent();
}
private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
isDragging = true;
offset = e.GetPosition(this);
CaptureMouse();
// 设置当前弹框的 Panel.ZIndex 为最高值
GlobalSetting.CurrentPageIndex++;
Panel.SetZIndex(this, GlobalSetting.CurrentPageIndex);
}
private void UserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
isDragging = false;
ReleaseMouseCapture();
}
private void UserControl_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
var parent = VisualTreeHelper.GetParent(this) as UIElement;
if (parent != null)
{
Point mousePos = e.GetPosition(parent);
double newX = mousePos.X - offset.X;
double newY = mousePos.Y - offset.Y;
Canvas.SetLeft(this, newX);
Canvas.SetTop(this, newY);
}
}
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
var parent = VisualTreeHelper.GetParent(this);
if (parent is Panel panel)
{
panel.Children.Remove(this);
}
}
public static DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string), typeof(CustomPopup));
public static DependencyProperty TitleBackgroundProperty =
DependencyProperty.Register("TitleBackground", typeof(Brush), typeof(CustomPopup));
public static DependencyProperty ShowCloseButtonProperty =
DependencyProperty.Register("ShowCloseButton", typeof(bool), typeof(CustomPopup));
public static DependencyProperty ContentProperty =
DependencyProperty.Register("Content", typeof(object), typeof(CustomPopup));
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public Brush TitleBackground
{
get { return (Brush)GetValue(TitleBackgroundProperty); }
set { SetValue(TitleBackgroundProperty, value); }
}
public bool ShowCloseButton
{
get { return (bool)GetValue(ShowCloseButtonProperty); }
set { SetValue(ShowCloseButtonProperty, value); }
}
public object Content
{
get { return GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
}
}
其他页面调用时