Moh*_*erm 5 c# drag-and-drop win-universal-app uwp windows-10-universal
我有一个针对本地银行的通用Windows应用程序,我正在进行汇款视图,他们需要使用UWP应用程序中的拖放功能从账户转账到账户.
我已经制作了动画部分,但是在将列表项放到"帐户到"列表后我需要帮助.
正如您在图片中看到的,我需要从"来自帐户"列表中拖动一个项目,并将其放在"到帐户"列表中的一个项目上.我怎样才能做到这一点?
我创建了一个小示例,它显示了两个填充了一些Accounts的ListView之间的拖放。我将跳过UserControls的实现- 页面 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>
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,有一个“源”列表,其中控件在被拖动时会触发一个事件。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
除了名称和余额之外,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;
}
}
Run Code Online (Sandbox Code Playgroud)
第一个为用户设置可接受的操作和一些信息。第二个将一些钱从一个帐户“转移”到第二个帐户。
一切看起来都是这样的:
您可以直接在 MS、其他文章和MS 示例存储库中找到更多帮助。