EventToCommand to get the item clicked inside an ItemsControl

497 Views Asked by At

This is the layout I have in the XAML:

<ScrollViewer Name="svDesigner" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Focusable="False">
    <ItemsControl ItemsSource="{Binding DesignerRowsCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <ItemsControl.ItemTemplate>
            <DataTemplate DataType="{x:Type base:UI_DesignerRow}">
                <cntrl:BabDesignerRow Margin="2"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <dxmvvm:Interaction.Behaviors>
            <dxmvvm:EventToCommand EventName="MouseLeftButtonDown" 
                               Command="{Binding SetPropertiesSourceCommand}" PassEventArgsToCommand="True">
                <dxmvvm:EventToCommand.EventArgsConverter>
                    <conv:DesignerItemClickEventArgsConverter/>
                </dxmvvm:EventToCommand.EventArgsConverter>
            </dxmvvm:EventToCommand>
        </dxmvvm:Interaction.Behaviors>
    </ItemsControl>

In the code behind I have this Sub which handles the ScrollViewer's PreviewMouseLeftButtonDown event:

Private Sub DesignerItemSelectionRedirect(sender As Object, e As MouseButtonEventArgs) Handles svDesigner.PreviewMouseLeftButtonDown

Inside my UserControl BabDesignerRow I have a lot of different UI object like TextBox, ComboBox, LayoutGroup and so on.

Right now, no matter where I click, I always get the entire ItemsControl as e.Source and not the real object selected.

Is there a way to get the object clicked inside my UserControl?

I need to get this information in order to highlight what the user selects.

1

There are 1 best solutions below

0
On

This is because of the routed event's tunneling strategy. You should read more about the routed events and their bubbling and tunneling strategies.

You can use the bubbling-like version of this event: MouseLeftButtonDown. As MSDN states:

Although this seems to follow a bubbling route through an element tree, it actually is a direct routed event that is raised and reraised along the element tree by each UIElement.

So it's not a truly bubbling event, but it should work for your case.

Alternatively, you can use the e.OriginalSource property instead of e.Source for obtaining the element that caused this event.