将 EventToCommandBehavior 与手势识别器结合使用

问题描述 投票:0回答:1

我有一个标签,用于通过点击导航到我的应用程序中的另一个页面。使用

Tapped
TapGestureRecognizer
效果很好,但是当尝试实现 MVVM 并将逻辑移出代码隐藏时,我在获取
Tapped
事件以在我的视图模型上触发命令时遇到了一些麻烦。

我可以通过以下实现来解决这个问题:

<Label Text="{Binding Name}">
    <Label.GestureRecognizers>
        <TapGestureRecognizer
            Command="{Binding Source={RelativeSource
                AncestorType={x:Type viewModels:HabitsOverviewViewModel}},
                Path=TapCommand}"
            CommandParameter="{Binding .}" />
    </Label.GestureRecognizers>
</Label>

但是对于其他事件,即

Appearing
,我已成功使用 MVVM 中的
EventToCommandBehaviour

为了一致性和可读性,我想在这里也使用

EventToCommandBehaviour
,但似乎无法让它工作。
TapGestureRecognizer
没有
Behaviours
属性,如果我在
Label.Behaviours
下定义它,
Tapped
不会被识别为有效事件。

此功能可用吗,还是我的代码错误?

这是我在几个不同的地方尝试过的

EventToCommandBehavior
,但点击没有任何作用(TappedCommand 存在于视图模型中,并在上面的实现中成功触发):

<Label Text="{Binding Name}">
    <Label.GestureRecognizers>
        <toolkit:EventToCommandBehavior
            Command="{Binding TapCommand}"
            CommandParameter="{Binding .}"
            EventName="Tapped"
            x:DataType="viewModels:MyViewModel" /> <!-- x:DataType is defined differently in the outer scope as this sits within a collection view -->
    </Label.GestureRecognizers>
</Label>
mvvm maui maui-community-toolkit
1个回答
1
投票

请参阅以下文章:标签

标签没有“Tap”或“Tapped”事件,因此您无法以这种方式使用 EventToCommandBehavior。使用 Tap 命令的正确方法就是您最初的做法。

© www.soinside.com 2019 - 2024. All rights reserved.