在WPF中,实现嵌套(分层)控件的拖放功能可以通过以下几个步骤来完成:
<Grid>
<StackPanel x:Name="stackPanel" AllowDrop="True">
<Button Content="Button1" />
<Button Content="Button2" />
<Button Content="Button3" />
</StackPanel>
</Grid>
<DataTemplate x:Key="DraggedButtonTemplate">
<Button Content="{Binding Content, RelativeSource={RelativeSource AncestorType=Button}}" />
</DataTemplate>
MouseMove="Button_MouseMove"
MouseLeftButtonUp="Button_MouseLeftButtonUp" />
private void Button_MouseMove(object sender, MouseEventArgs e)
{
Button button = sender as Button;
DataObject data = new DataObject(typeof(Button), button);
DragDrop.DoDragDrop(button, data, DragDropEffects.Move);
}
private void Button_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Button button = sender as Button;
DataObject data = new DataObject(typeof(Button), button);
DragDrop.DoDragDrop(button, data, DragDropEffects.Move);
}
AllowDrop="True"
DragEnter="StackPanel_DragEnter"
DragLeave="StackPanel_DragLeave"
Drop="StackPanel_Drop" />
private void StackPanel_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Button)))
{
e.Effects = DragDropEffects.Move;
}
else
{
e.Effects = DragDropEffects.None;
}
}
private void StackPanel_DragLeave(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.None;
}
private void StackPanel_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Button)))
{
Button button = e.Data.GetData(typeof(Button)) as Button;
Point point = e.GetPosition(stackPanel);
button.RenderTransform = new TranslateTransform(point.X, point.Y);
stackPanel.Children.Add(button);
}
}
通过以上步骤,可以实现WPF中嵌套(分层)控件的拖放功能。
领取专属 10元无门槛券
手把手带您无忧上云