列表框中包含一些项目。还有一个3x3矩阵的网格。用户将拖动一个项目并将一个网格单元格放在其中。
我发现的大部分样本都是关于从一个列表框拖放到另一个列表框。但我想放入一个网格单元格。我怎样才能做到这一点?
请指教。谢谢 PJ
答案 0 :(得分: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();
}
}
希望这有帮助,尊重