gpt4 book ai didi

c# - 如何在 C# WPF 中通过拖放交换两个标签的数据?

转载 作者:太空狗 更新时间:2023-10-30 01:30:44 26 4
gpt4 key购买 nike

我想做类似的事情 我有两个标签

A .................. B
______ ............ ________
|红色 | ………… |绿色 |
------------ .......... ------------

当我将 A 拖到 B 或将 B 拖到 A 时,两者的文本交换

A .................. B
______ ...... ______
|绿色| ………… |红色 |
------------ .....................

我做了一点

主窗口
main window

当我拖放代码中的文本时,会出现在放置标签上

当我在绿色上拖动红色时:
When I drag red on green

我的代码:

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

最佳答案

这是我如何实现的。

下面是我的 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>

下面是我的代码隐藏事件

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

所以基本上我创建了一个全局标签 DraggingLabel 以在 Label_Drop 处使用它来交换文本。

最终输出。

enter image description here

祝你好运。

关于c# - 如何在 C# WPF 中通过拖放交换两个标签的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com