2010-01-27 86 views
2

有一個列表框,其中包含一些項目。還有一個3x3矩陣的網格。用戶將拖動一個項目並放置一個網格單元格。在ListBox項目和WPF中的網格單元之間拖放?

我發現的大多數樣本都是關於從一個列表框拖放到另一個列表框的。但我想放入一個網格單元。我怎樣才能做到這一點?

請指教。感謝 PJ

回答

4

請,檢查下面的例子會爲你工作:

XAML:

<Grid> 
    <ListBox Height="100" HorizontalAlignment="Left" Margin="56,65,0,0" 
      Name="listBox1" VerticalAlignment="Top" Width="120" 
      PreviewMouseLeftButtonDown="listBox1_PreviewMouseLeftButtonDown"> 
     <ListBoxItem Content="one" /> 
     <ListBoxItem Content="two" /> 
     <ListBoxItem Content="three" /> 
    </ListBox> 
    <Grid Height="100" HorizontalAlignment="Left" Margin="238,65,0,0" Name="grid1" 
      VerticalAlignment="Top" Width="200" ShowGridLines="True" TextBlock.Drop="grid1_Drop"> 
     <Grid.RowDefinitions> 
      <RowDefinition /> 
      <RowDefinition /> 
     </Grid.RowDefinitions> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition /> 
      <ColumnDefinition /> 
     </Grid.ColumnDefinitions> 

     <TextBlock Grid.Row="0" Grid.Column="0" AllowDrop="True"></TextBlock> 
     <TextBlock Grid.Row="0" Grid.Column="1" AllowDrop="True"></TextBlock> 
     <TextBlock Grid.Row="1" Grid.Column="0" AllowDrop="True"></TextBlock> 
     <TextBlock Grid.Row="1" Grid.Column="1" AllowDrop="True"></TextBlock> 

    </Grid> 
</Grid> 

代碼:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    private void listBox1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
    { 
     object item = listBox1.SelectedItem; 
     if (item != null) 
      DragDrop.DoDragDrop(listBox1, item, DragDropEffects.Move); 
    } 

    private void grid1_Drop(object sender, RoutedEventArgs e) 
    { 
     TextBlock textBlock = e.Source as TextBlock; 
     Console.WriteLine("drop item into grid column:{0} row:{1}", 
      Grid.GetColumn(textBlock), Grid.GetRow(textBlock)); 

     DataObject item = (((DragEventArgs)e).Data) as DataObject; 
     ListBoxItem listItem = item.GetData(typeof(ListBoxItem)) as ListBoxItem; 
     textBlock.Text = listItem.Content.ToString(); 
    } 
} 

希望這會有所幫助,至於

+0

感謝爲迴應。儘管小問題..在網格xaml代碼中,以下代碼是不可接受的。 TextBlock.Drop =「grid1_Drop」 您意味着要附加處理程序的事件? – 2010-01-31 06:14:50

+1

嗯..對我來說工作很不錯;我在發佈之前實際上已經嘗試過這些代碼您可以嘗試將放置事件定義移至xaml中的文本框 – 2010-01-31 18:43:37