需求:
作为一名程序员,相信大家都已经接触过大名鼎鼎的原型设计工具Axure,没用过的一定要去了解一下,本文要使用WPF实现树控件节点拖动功能。
- 实现拖动到目标节点的子目录中
- 实现拖动到目标节点的同级目录中
实现:
原理:树节点由图片和文本构成,当拖动节点移动到目标节点的图片上时认为是拖动到目标节点的同级目录;当拖动节点到目标节点的文本上时认为是拖动到目标节点的子目录。使用EventSetter和事件实现标识是拖动到目标节点同级目录,还是拖动到目标节点子目录功能;DataTrigger实现拖动到图片上和文本上的节点显示效果。
前台代码:
<Window x:Class="DragTree.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DragTree"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<HierarchicalDataTemplate x:Key="TreeViewDropItemTemplate" ItemsSource="{Binding Childern}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="16"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Image x:Name="img" Grid.Column="0" Margin="2,0" Source="{Binding BI}">
<Image.Style>
<Style>
<EventSetter Event="Image.MouseEnter" Handler="Image_MouseEnter"/>
<EventSetter Event="Image.MouseLeave" Handler="Image_MouseLeave"/>
</Style>
</Image.Style>
</Image>
<TextBlock x:Name="tb" Grid.Column="1" Text="{Binding Name}">
<TextBlock.Style>
<Style>
<EventSetter Event="TextBlock.MouseEnter" Handler="TextBlock_MouseEnter"/>
<EventSetter Event="TextBlock.MouseLeave" Handler="TextBlock_MouseLeave"/>
</Style>
</TextBlock.Style>
</TextBlock>
<Grid x:Name="r1" Grid.Row="1" Grid.ColumnSpan="2" Height="4" Visibility="Collapsed">
<Ellipse Fill="Blue" StrokeThickness="0" Width="4" Height="4" HorizontalAlignment="Left"/>
<Rectangle Fill="Blue" StrokeThickness="0" Height="1" VerticalAlignment="Center"/>
</Grid>
<Grid x:Name="r2" Grid.Row="1" Grid.Column="1" Height="4" Visibility="Collapsed">