gpt4 book ai didi

c# - 在WPF C#中的wrappanel内部重新排列CustomControl

转载 作者:行者123 更新时间:2023-12-03 18:47:15 26 4
gpt4 key购买 nike

我在包装面板内部动态创建一个customcontrol。现在,我需要对包装面板中的自定义控件进行重新排序。是否可以通过拖放在包装面板内部重新排列自定义控件?

这是我的XAML代码

<DockPanel Grid.Column="1" Margin="208,40,1,94" Grid.Row="2"
Background="White" AllowDrop="True">
<ScrollViewer AllowDrop="True" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden" Width="443">
<StackPanel Width="443" >


<WrapPanel x:Name="pnl" HorizontalAlignment="Left"
Height="Auto"
VerticalAlignment="Top" Width="480" AllowDrop="True"
/>

</StackPanel>
</ScrollViewer>
</DockPanel>


我已经尝试将自动换行面板放在列表中,如给定答案(Ilan的答案)所建议的那样,现在我的面板在后面的代码中无法访问。我做错什么了吗?

enter image description here

最佳答案

Drag Drop in a WrapPanel

在这里,我演示了Buttons,您可以根据需要对其进行修改。

Xaml

<WrapPanel x:Name="Pnl" Background="Yellow" Margin="0,0,0,128" Button.DragEnter="Button_DragEnter" Button.MouseRightButtonDown="Button_MouseDown">
<Button Content="Btn1" AllowDrop="True"/>
<Button Content="Btn2" AllowDrop="True"/>
<Button Content="Btn3" AllowDrop="True"/>
</WrapPanel>




Button btn_to_drag;
private void Button_MouseDown(object sender, MouseButtonEventArgs e)
{
btn_to_drag = (Button)e.Source;
DragDrop.DoDragDrop(btn_to_drag, btn_to_drag, DragDropEffects.Move);
}

private void Button_DragEnter(object sender, DragEventArgs e)
{
Button btn = (Button)e.Source;
int where_to_drop = Pnl.Children.IndexOf(btn);
Pnl.Children.Remove(btn_to_drag);
Pnl.Children.Insert(where_to_drop, btn_to_drag);
}


使用 DataObject的另一种方法消除了对 btn_to_drag声明的需要。

private void Button_MouseDown(object sender, MouseButtonEventArgs e)
{
    DataObject data = new DataObject(DataFormats.Serializable, (Button)e.Source );
    DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Move);
}

private void Button_DragEnter(object sender, DragEventArgs e)
{
    Button btn_to_move = (Button) e.Data.GetData(DataFormats.Serializable);
            
    int where_to_move = Pnl.Children.IndexOf((UIElement)e.Source);
    int what_to_move = Pnl.Children.IndexOf(btn_to_move);

    Pnl.Children.RemoveAt(what_to_move);
    Pnl.Children.Insert(where_to_move, btn_to_move);
}

关于c# - 在WPF C#中的wrappanel内部重新排列CustomControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36642622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com