UWP: How to catch the click of a listview part fro

2019-04-13 16:22发布

I have this listview:

<Page
    x:Class="DataBase.ControlsPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding CustomersViewModel, Source={StaticResource ViewModelLocator}}">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <ListView Name="HeaderList" ItemsSource="{Binding Customers}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Border Background="Bisque">
                            <TextBlock Text="{Binding Name"/>
                        </Border>
                        <ListView Name="SubItemsList" ItemsSource="{Binding Project}" ItemClick="SubItemClick">
                        <x:String>SubItem 1</x:String>
                        <x:String>SubItem 2</x:String>
                        <x:String>SubItem 3</x:String>
                        </ListView>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        <x:String>Item 1</x:String>
        <x:String>Item 2</x:String>
        <x:String>Item 3</x:String>
        </ListView>
    </Grid>
</Page>

All I want is to catch the click of a subItem(ItemClick="SubItemClick">) in my CustomersViewModel. Is that possible? I know for the sub-items list items, the data is a Project which is just a data model, it does not contain any click handler. But, how can I catch the click in the view model and not in the code-behind?

Also I'm uploading a picture to visualise what I want:

enter image description here

2条回答
男人必须洒脱
2楼-- · 2019-04-13 16:32

What you really need is a ClickCommand in your viewmodel. But since the ListView control doesn't expose a ItemClickCommand, one common way is to use a behavior to establish the connection between your ClickCommand and the ItemClick event.

This particular behavior you are looking for is called InvokeCommandAction, which can be found in this nuget package.

Basically the end result would look something like this -

<ListView Name="HeaderList" ItemsSource="{Binding Customers}">
    <Interactivity:Interaction.Behaviors>
        <Interactions:EventTriggerBehavior EventName="ItemClick" SourceObject="{Binding ElementName=HeaderList}">
            <Interactions:InvokeCommandAction Command="{Binding ClickCommand}"/>
        <Interactions:EventTriggerBehavior>
    <Interactivity:Interaction.Behaviors>
查看更多
干净又极端
3楼-- · 2019-04-13 16:40

As Justin XL said, the answer I was looking for is this: ItemClick="{Binding DataContext.ClickCommand, ElementName=HeaderList}"

查看更多
登录 后发表回答