2013-11-20 52 views
2

我是WPF新手,请耐心等待。在UniformGrid中,我放置了多个在运行时创建的UserControl。我想知道的是如何在运行时拖放,移动或交换这些控件的位置。我在互联网上搜索了所有内容,但找不到任何有用的东西。在统一网格内拖放项目

回答

1

UniformGrid是一个布局控件。你不能直接与它互动。

为了达到您的需要,我为您提供这个解决方案。

  1. 创建ItemsControl元素
  2. 更改ItemsPanelUniformGrid
  3. 使用GongSolutions.Wpf.DragDrop project。您可以从nuGet安装它http://www.nuget.org/packages/gong-wpf-dragdrop/

此解决方案可以在没有任何代码隐藏或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> 
+0

我怎么能在运行时动态在ItemsControl中添加项目?正如我在统一网格中一样,我在运行时拖放项目。 – mrafiraza

+0

将ItemsControl ItemsSource绑定到ObservableCollection 。你需要帮助吗? – sacha

+0

是的。我会非常感谢你。 – mrafiraza