感觉这玩意之前一直没用过,可能在容器里用到的比较多吧,记录一下。
第一种代码法:
cs
Style itemContainerStyle = new Style(typeof(ListBoxItem));
itemContainerStyle.Setters.Add(new Setter(ListBoxItem.AllowDropProperty, true));
itemContainerStyle.Setters.Add(new EventSetter(ListBoxItem.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(s_PreviewMouseLeftButtonDown)));
itemContainerStyle.Setters.Add(new EventSetter(ListBoxItem.DropEvent, new DragEventHandler(listbox1_Drop)));
listbox1.ItemContainerStyle = itemContainerStyle;
第二种xaml法:
XML
<ListBox>
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="AllowDrop" Value="True" />
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="s_PreviewMouseLeftButtonDown" />
<EventSetter Event="Drop" Handler="listbox1_Drop" />
</Style>
</ListBox.Resources>
</ListBox>
如果使用MVVM框架可以使用Binding:
XML
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="{Binding s_PreviewMouseLeftButtonDown}" />
<EventSetter Event="Drop" Handler="{Binding listbox1_Drop}" />