Monday, April 1, 2013

Drag Drop between datagrid cells


If you’ve been searching the web for a good sample of how to drag and drop data from one DataGrid to another in Silverlight, you’ve probably found some great samples out there, showing “how easy” it can be by just surrounding your.  In fact, if you do that, you can drag and drop data from one grid cell to the other.  The problem is that most of these demos are about the visual aspect of drag and drop.  But in the real world, there is more work to be done.  Most of the samples that I found did not deal with how to save the data once it was dropped in the other grid.
The Firsr XAML Code
<sdk:DataGrid Grid.Row="1" x:Name="dg" ItemsSource="{Binding Data}" AutoGenerateColumns="False" IsReadOnly="True" >
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="Id" Binding="{Binding Id}" />
                <sdk:DataGridTemplateColumn Header="FirstName" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto" >
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text ="{Binding FirstName}"  
                                       MouseLeftButtonDown="TextBox_MouseLeftButtonDown" 
                                       MouseLeftButtonUp="TextBox_MouseLeftButtonUp"
                                       MouseMove="TextBlock_MouseMove"/>
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellTemplate>
                </sdk:DataGridTemplateColumn>
                <sdk:DataGridTemplateColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto" >
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding LastName}" MouseLeftButtonDown="TextBox_MouseLeftButtonDown" MouseLeftButtonUp="TextBox_MouseLeftButtonUp"/>
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellTemplate>
                </sdk:DataGridTemplateColumn>
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>

The C# Code
private void TextBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            dragText = string.Empty;
            TextBlock tb = sender as TextBlock;
            dragTextBox = tb;
            dragText = tb.Text;
        }

        private void TextBox_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            dragTextBox.Text = tb.Text;
            tb.Text = dragText;
        }

        private void TextBlock_MouseMove(object sender, MouseEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            tb.Cursor = Cursors.Hand;
        }

No comments:

Post a Comment