我正在尝试实现拖放。所以我需要在事件处理程序中开始拖动操作。如何正确设置事件处理程序的样式?
看看我的代码
<UserControl x:Class="MyProject.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<ListBox ItemsSource="{Binding MyItems}" DisplayMemberPath="Name">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<EventSetter Event="MouseDown" Handler="OnMouseDownStartDrag" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</UserControl>
我试图在后面的代码中调用OnMouseDownStartDrag,在用户控件的视图模型中,其中存在MyItems以及MyItems的单个元素(某些数据类)。
不幸的是,从未调用OnMouseDownStartDrag。我错过了什么?风格有问题吗?我应该在哪里放置OnMouseDownStartDrag以及应该以哪种方式调用它?
我使用 WPF 4.6.2
根据这篇文章,问题似乎不在于您如何设置或在哪里设置 EventHandler 。
您应该尝试使用PreviewMouseDown而不是MouseDown。所以,它会像
<UserControl x:Class="MyProject.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<ListBox ItemsSource="{Binding MyItems}" DisplayMemberPath="Name">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<EventSetter Event="PreviewMouseDown" Handler="OnMouseDownStartDrag" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
我已经尝试过从样式设置它的代码并且它有效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句