views:

610

answers:

1

Hi There is a list box with some 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

+1  A: 

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

serge_gubenko
thanks for the response. small issue though.. In grid xaml code, following code is not acceptable.TextBlock.Drop="grid1_Drop"To which event you mean to attach the handler?
AJ
hmm.. works pretty fine for me; I actually tried the code before posting it. You can try moving the drop event definition to text boxes in your xaml
serge_gubenko