我已经创建了一个小样本 https://github.com/Romasz/UWPSamples/tree/master/AccountDragDrop显示两个之间的拖放列表视图充满了一些Accounts。我将跳过执行用户控件- 页面 xaml 如下所示:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="200"/>
<RowDefinition Height="200"/>
</Grid.RowDefinitions>
<ListView Header="Source" Margin="10" Grid.Row="0" CanDragItems="True" ItemsSource="{x:Bind Accounts}" SelectionMode="None">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<controls:AccountControl CanDrag="True" DragStarting="AccountControl_DragStarting"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<ListView Header="Targets" Margin="10" Grid.Row="1" ItemsSource="{x:Bind Accounts}" SelectionMode="None">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<controls:AccountControl AllowDrop="True" DragEnter="AccountControl_DragEnter" Drop="AccountControl_Drop"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
正如你所看到的,有一个Source控件在其中被拖动时触发事件的列表。
private void AccountControl_DragStarting(UIElement sender, DragStartingEventArgs args)
{
if ((sender as AccountControl)?.DataContext is Account account)
{
args.AllowedOperations = DataPackageOperation.Link;
args.Data.SetData(accountId, account.Id);
}
}
The Account除了名称和余额之外的类还有一个Guid标识符,以便我可以使用它来传递在传输方法中使用了哪个源帐户的信息。
第二个列表中的项目 (Targets) 仅接受放置操作,并为此目的触发两个事件:
private void AccountControl_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Link;
e.DragUIOverride.Caption = "Transfer";
}
private async void AccountControl_Drop(object sender, DragEventArgs e)
{
if ((e.OriginalSource as AccountControl)?.DataContext is Account targetAccount)
if (await (e.DataView.GetDataAsync(accountId)) is Guid sourceAccountId)
{
var sourceAccount = Accounts.First(x => x.Id == sourceAccountId);
sourceAccount.Balance -= 1000;
targetAccount.Balance += 1000;
}
}
第一个为用户设置可接受的操作和一些信息。第二个将一些钱从一个帐户“转移”到第二个帐户。
一切看起来都是这样的:
您可以在以下位置找到更多帮助直接MS https://learn.microsoft.com/en-us/windows/uwp/app-to-app/drag-and-drop, 其他文章 https://msdn.microsoft.com/en-us/magazine/mt185571.aspx and in MS 样本存储库 https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/XamlDragAndDrop.