How can I make Exchange data from two labels when dragging and dropping in C # WPF?

I want to do something like I have two shortcuts

A ......................... B
______........... _______
| RED | .......... | GREEN | ----------.......... -----------

When I drag A to B OR B to A, the exchange text

A ......................... B
______.............. _____
| GREEN | .......... | RED | ----------............... ---------

I did it a bit

main window
main window

When I drag text from code , drop label appears

When I drag red to green:
When I drag red on green

My code is:

    private void Label_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Label lblFrom = e.Source as Label;


        if (e.LeftButton == MouseButtonState.Pressed)
            DragDrop.DoDragDrop(lblFrom, lblFrom.Content, DragDropEffects.Copy);
    }

    private void Label_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
    {
        Label lblFrom = e.Source as Label;

        if (!e.KeyStates.HasFlag(DragDropKeyStates.LeftMouseButton))
            lblFrom.Content = "RED";

    }

    private void Label_Drop(object sender, DragEventArgs e)
    {
        string draggedText = (string)e.Data.GetData(DataFormats.StringFormat);

        Label toLabel = e.Source as Label;
        toLabel.Content = draggedText;
    }
}
+4
source share
1

.

XAML.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Label Width="50" Height="50" Background="Red" Content="Red" HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" MouseDown="Label_MouseDown" Drop="Label_Drop" AllowDrop="True"/>
    <Label Width="50" Height="50" Background="Green" Content="Green" HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Grid.Column="1" MouseDown="Label_MouseDown" Drop="Label_Drop" AllowDrop="True"/>
</Grid>

CodeBehind

Label DraggingLabel;
private void Label_MouseDown(object sender, MouseButtonEventArgs e)
{
    DraggingLabel = sender as Label;
    if (e.LeftButton == MouseButtonState.Pressed)
        DragDrop.DoDragDrop(DraggingLabel, DraggingLabel.Content, DragDropEffects.Copy);
}

private void Label_Drop(object sender, DragEventArgs e)
{
    Label originalsource = e.OriginalSource as Label;
    Label lblToDrop = sender as Label;
    string fromContent = lblToDrop.Content.ToString();
    lblToDrop.Content = (string)e.Data.GetData(DataFormats.StringFormat);
    DraggingLabel.Content = fromContent;
}

, Label DraggingLabel, Label_Drop .

.

enter image description here

.

+3

Source: https://habr.com/ru/post/1675093/


All Articles