Can I enable PreviewClick using InputBindings in W

2019-03-06 00:51发布

问题:

I want to detect when a user clicks on an item on a listview, without using events as I do command binding and I don't like all the nonsense of the behaviours. I have tried this:

<ListView x:Name="MainList" Margin="2,8,6,8" Background="Black" 
   ItemsSource="{Binding Path=AssetsVM.Data, Mode=OneWay}" 
   BorderBrush="{x:Null}" >

    <ListView.InputBindings>
         <MouseBinding Command="{Binding Path=AssetsVM.SelectActivo}" 
            CommandParameter="{Binding ElementName=MainList, Path=SelectedItem}" 
            MouseAction="LeftClick" />
    </ListView.InputBindings>

This works fine if I click on the listview but does not work on the items. What I need is either a way to enable "Preview" or have a MouseAction/Gesture that behaves as preview. Are either one of these possible?

回答1:

When using a command-driven architecture like this, I usually use AttachedCommandBehavior to get around the fact that Microsoft did not make MouseBinding.Command a DependencyProperty. An example of how to do get the functionality you want using this approach is shown below:

<ListView x:Name="MainList" ItemsSource="{Binding Path=AssetsVM.Data, Mode=OneWay}">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Style.Setters>
                <Setter Property="acb:CommandBehavior.Event" Value="Selected" />
                <Setter Property="acb:CommandBehavior.Command" Value="{Binding DataContext.AssetsVM.SelectActivo, ElementName=MainList}" />
                <Setter Property="acb:CommandBehavior.CommandParameter" Value="{Binding}" />
            </Style.Setters>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>