Blend自带的行为MouseDragElementBehavior应用到ListBox后,如果用鼠标按住列表列拖动,没有任何效果,在多次尝试中意外发现,如果将ListBox的边框设置成一个较大值,在边框上点击时,却可以拖动,但是一般开发中,没人会把ListBox设置一个粗粗的难看边框。于是想到了下面的变通解决办法:当鼠标进入时显示边框,鼠标离开时再隐藏边框。
示例代码:
Xaml部分
代码语言:javascript复制<UserControl
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:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" x:Class="sl_drag_sample.MainPage"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<ListBox x:Name="lbSample" MinHeight="50" MinWidth="100" BorderThickness="0" HorizontalAlignment="Center" VerticalAlignment="Center" MouseEnter="ShowBorder" MouseLeftButtonUp="HideBorder" MouseLeftButtonDown="ShowBorder" MouseMove="ShowBorder" MouseLeave="HideBorder">
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior/>
</i:Interaction.Behaviors>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="这是测试文字">
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior/>
</i:Interaction.Behaviors>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
Xaml.cs部分
代码语言:javascript复制using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace sl_drag_sample
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded = new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
char[] s = "ABCDE".ToCharArray();
lbSample.ItemsSource = s;
}
private void ShowBorder(object sender, MouseEventArgs e)
{
(sender as ListBox).BorderThickness = new Thickness(20.0);
}
private void HideBorder(object sender, MouseEventArgs e)
{
(sender as ListBox).BorderThickness = new Thickness(0.0);
}
}
}