我是WPF的新手所以请耐心等待。在UniformGrid中,我放置了多个在运行时创建的UserControl。我想知道的是如何在运行时拖放,移动或交换这些控件的位置。我在互联网上搜索过但找不到任何有收获的东西。
答案 0 :(得分:1)
UniformGrid
是布局控件。你不能直接与它互动。
为了达到你所需要的,我建议你这个解决方案。
ItemsControl
元素ItemsPanel
更改为UniformGrid
此解决方案可以在没有任何代码隐藏或VM代码的情况下编写。
<Window x:Class="WpfApplication6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:dd="clr-namespace:GongSolutions.Wpf.DragDrop;assembly=GongSolutions.Wpf.DragDrop"
Title="MainWindow" Height="350" Width="525">
<ItemsControl Height="150"
dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="True">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Items>
<system:String>Item 1</system:String>
<system:String>Item 2</system:String>
<system:String>Item 3</system:String>
</ItemsControl.Items>
</ItemsControl>
</Window>
<强>更新强>
如果您需要从其他控件拖动项目,请将其添加到您的代码隐藏文件中。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
SourceOfItems = new List<string>() { "Source 1", "Source 2", "Source 3" };
Items = new ObservableCollection<string>() { "Item 1", "Item 2", "Item 3" };
}
public ObservableCollection<string> Items { get; private set; }
public List<string> SourceOfItems { get; private set; }
}
并像这样更新您的XAML:
<Window x:Class="WpfApplication6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dd="clr-namespace:GongSolutions.Wpf.DragDrop;assembly=GongSolutions.Wpf.DragDrop"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ListBox ItemsSource="{Binding SourceOfItems}"
dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="False"/>
<ItemsControl Height="150"
dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="True"
ItemsSource="{Binding Items}"
Background="Plum"
>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
</Window>