I'm trying to implement drag&drop. So I need to start the dragging operation in an eventhandler. How do I have to set the eventhandler in a style correctly?
Have a look at my code
<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>
I've tried to call OnMouseDownStartDrag in code behind, in the viewmodel of the usercontrol, where MyItems exists and in the single element of MyItems (some data class).
Unfortunately, OnMouseDownStartDrag is never called. What am I missing? Is something wrong with the style? Where should I place OnMouseDownStartDrag and in which way should it be called?
I using WPF 4.6.2
CodePudding user response:
Seems like the problem is not in how you set or where you set the EventHandler according to this post.
You should try the PreviewMouseDown instead of MouseDown. So, it will be like
<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>
I have tried that code with setting it from the style and it works.