WPF의 Popup 을 Drag Move 가 되도록 처리하는 방법입니다.
Behavior를 이용해서 처리하며
.NET 7.0 기준 Nuget Package 'Microsoft.Xaml.Behaviors.Wpf' 을 설치해야 합니다.
DragMovePopupBehavior.cs
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using Microsoft.Xaml.Behaviors;
namespace Wpf.PopupMoveTest
{
public class DragMovePopupBehavior : Behavior<Popup>
{
protected override void OnAttached()
{
if (this.AssociatedObject.Child != null)
{
if (this.AssociatedObject.Child is Panel)
{
Thumb thumb = new Thumb() { Width = 0, Height = 0 };
var panel = this.AssociatedObject.Child as Panel;
if (panel != null)
{
panel.Children.Add(thumb);
}
this.AssociatedObject.MouseDown += (s, e) =>
{
thumb.RaiseEvent(e);
};
thumb.DragDelta += (s, e) =>
{
this.AssociatedObject.HorizontalOffset += e.HorizontalChange;
this.AssociatedObject.VerticalOffset += e.VerticalChange;
};
}
}
}
}
}
Popup 에 아래처럼 Behavior를 이용하여 처리하면 됩니다.
<Popup>
......
<behaviors:Interaction.Behaviors>
<local:DragMovePopupBehavior />
</behaviors:Interaction.Behaviors>
</Popup>
MainWindow.xaml
<Window
x:Class="Wpf.PopupMoveTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:behaviors="http://schemas.microsoft.com/xaml/behaviors"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Wpf.PopupMoveTest"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Grid>
<ToggleButton
x:Name="toggleButton"
Width="100"
Height="30"
VerticalAlignment="Top"
Content="Show Popup" />
<Popup IsOpen="{Binding ElementName=toggleButton, Path=IsChecked}" Placement="Center">
<StackPanel Background="Black">
<Label Content="Popup Darg Move Test" Foreground="White" HorizontalAlignment="Center"/>
<Grid
Width="300"
Height="150"
Background="Blue">
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="50"
Foreground="White"
Text="KJUN.KR"
TextAlignment="Center" />
</Grid>
</StackPanel>
<behaviors:Interaction.Behaviors>
<local:DragMovePopupBehavior />
</behaviors:Interaction.Behaviors>
</Popup>
</Grid>
</Window>
결과
팝업의 헤더를 클릭해 움직이면 팝업이 이동됩니다.
[Source]
https://github.com/kei-soft/Wpf.PopupMoveTest
WPF PriorityBinding (0) | 2024.10.14 |
---|---|
WPF ColorSlider 만들기 (0) | 2024.10.07 |
WPF Parent Binding (0) | 2024.10.06 |
WPF Font 적용하기 (0) | 2024.10.01 |
WPF Freezable (0) | 2024.09.27 |