[英]How can I do Exchange data of two labels on drag and drop in C# WPF?
我想做一些像我有兩個標簽的事情
A .............. ........... B.
______ ........... _______
| RED | .......... | 綠色|
---------- .......... -----------
當我在兩個交易所的文本拖動一個在B或B
A .............. ........... B.
______ ............ _____
| GREEN | .......... | RED |
---------- ............... ---------
我做了一點
主窗口
當我拖放代碼中的文本時,會在drop標簽上顯示
當我在綠色上拖動紅色時:
我的代碼:
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>
以下是我的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中使用它來交換Text。
最終產出。
祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.