播放地址:20241120-.NET9.0+WPF实战三类流程化业务逻辑控制-10_哔哩哔哩_bilibili
第6课 使用ViewModel绑定的方式实现拖拽
创建MainViewModel.cs文件
1 public class MainViewModel 2 { 3 public ObservableCollection<string> ProcessList { get; set; } = new ObservableCollection<string>(); 4 5 public void ListViewItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 6 { 7 DragDrop.DoDragDrop((DependencyObject)sender, (sender as ListViewItem).Content, DragDropEffects.Copy); 8 } 9 10 public void ListBox_Drop(object sender, DragEventArgs e) 11 { 12 string value = e.Data.GetData(typeof(string)).ToString(); 13 (sender as ListBox).Items.Add(new ListBoxItem() { Content = value }); 14 } 15 }
Nuget搜索behaviors安装Microsoft.Xaml.Behaviors.Wpf 版本1.1.135
MainView.xaml文件修改Window节点增加属性:
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
然后就可以修改节点ListView下面的ListViewItem增加子节点:
1 <i:Interaction.Triggers> 2 <i:EventTrigger EventName="PreviewMouseLeftButtonDown"> 3 <i:CallMethodAction MethodName="ListViewItem_MouseLeftButtonDown" TargetObject="{Binding}" /> 4 </i:EventTrigger> 5 </i:Interaction.Triggers>
然后修改ListBox节点下面新增子节点
<i:Interaction.Triggers> <i:EventTrigger EventName="Drop"> <i:CallMethodAction MethodName="ListBox_Drop" TargetObject="{Binding}" /> </i:EventTrigger> </i:Interaction.Triggers>
最终MainView.xaml文件中代码如下:
1 <Window x:Class="WpfApp1.MainView" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:WpfApp1" xmlns:i="http://schemas.microsoft.com/xaml/behaviors" 7 mc:Ignorable="d" 8 WindowStartupLocation="CenterScreen" 9 Background="White" 10 Title="MainView" Height="650" Width="1300"> 11 <Grid> 12 <Grid.ColumnDefinitions> 13 <ColumnDefinition Width="200" /> 14 <ColumnDefinition Width="300" /> 15 <ColumnDefinition /> 16 </Grid.ColumnDefinitions> 17 <ListView> 18 <ListViewItem Content="AAA"> 19 <i:Interaction.Triggers> 20 <i:EventTrigger EventName="PreviewMouseLeftButtonDown"> 21 <i:CallMethodAction MethodName="ListViewItem_MouseLeftButtonDown" TargetObject="{Binding}" /> 22 </i:EventTrigger> 23 </i:Interaction.Triggers> 24 </ListViewItem> 25 <ListViewItem Content="BBB"></ListViewItem> 26 <ListViewItem Content="CCC"></ListViewItem> 27 <ListViewItem Content="DDD"></ListViewItem> 28 </ListView> 29 <ListBox Grid.Column="1" AllowDrop="True" ItemsSource="{Binding ProcessList}"> 30 <i:Interaction.Triggers> 31 <i:EventTrigger EventName="Drop"> 32 <i:CallMethodAction MethodName="ListBox_Drop" TargetObject="{Binding}" /> 33 </i:EventTrigger> 34 </i:Interaction.Triggers> 35 </ListBox> 36 </Grid> 37 </Window>
运行测试拖拽功能基本上还可以操作,最终松开鼠标时会有报错
标签:sender,流程化,节点,WPF,public,NET9.0 From: https://www.cnblogs.com/uxinxin/p/18585564