UWP: How to catch the click of a listview part from another listview in the viewmodel instead of code-behind?

江枫思渺然 提交于 2019-12-21 21:38:24

问题


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:


回答1:


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>



回答2:


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



来源:https://stackoverflow.com/questions/42026392/uwp-how-to-catch-the-click-of-a-listview-part-from-another-listview-in-the-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!