开发者

Drag and drop between ListBox items and Grid cells in WPF?

There is a list box with 开发者_如何学Pythonsome items in it. Also there is a grid with 3x3 matrix. The user will be dragging an item and dropping on one the cells of grid.

Most of the samples I found are about dragging-dropping from one listbox to another listbox. But I want to drop in one cell of grid. How can I achieve this?

Please advise. thanks PJ


pls, check if an example below would work for you:

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>

code:

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();
    }
}

hope this helps, regards

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜