【问题标题】:Listen to ItemTapped Event in FreshMvvm在 FreshMvvm 中监听 ItemTapped 事件
【发布时间】:2016-10-22 15:07:25
【问题描述】:

在我的项目中,我有一个列表视图,现在听 SelectedItem 更改很容易,每个教程都有,但我找不到任何关于使用 ItemTapped 事件的内容。

我在模型页面中将事件绑定到什么?

谢谢,

迈克

【问题讨论】:

    标签: mvvm xamarin.forms freshmvvm


    【解决方案1】:

    由于ItemTapped 是一个事件而不是Command(或根本不是BindableProperty),因此您不能直接从PageModel 那里使用它。

    他们为此发明了类似Behaviors 的东西。通过行为,您可以将 Event 转换为 Command

    虽然有像Corcav's one 这样的第三方插件,但它也内置在Xamarin.Forms now 中。

    让我用 Corcav 解释一下,其他实现应该类似。另外我假设您使用的是 XAML。

    首先,安装 NuGet,不要忘记在页面中包含正确的命名空间,这意味着添加类似:xmlns:behaviors="clr-namespace:Corcav.Behaviors;assembly=Corcav.Behaviors"

    现在在您的ListView 下声明您的Behaviors,如下所示:

    <!-- ... more XAML here ... -->
    <ListView IsPullToRefreshEnabled="true" RefreshCommand="{Binding RefreshDataCommand}" IsRefreshing="{Binding IsBusy}"  IsVisible="{Binding HasItems}" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" CachingStrategy="RecycleElement">
            <behaviors:Interaction.Behaviors>
              <behaviors:BehaviorCollection>
                <behaviors:EventToCommand EventName="ItemSelected" Command="{Binding ItemSelectedCommand}" />
              </behaviors:BehaviorCollection>
            </behaviors:Interaction.Behaviors>
    
    <!-- ... more XAML here ... -->
    

    请注意,这是一个集合,因此您可以根据需要添加更多(在其他情况下也是如此)。 另请注意,我确实实际上也使用了SelectedItem。这可能是您想要的,因为否则您点击的项目将保持选中状态。所以SelectedItem 属性除了将它设置回null(因此是TwoWay)之外没有做更多的事情。但是您也可以从那里获取实际选择的项目。

    所以现在在您的PageModel 中声明一个命令并分配如下内容:

    private void ItemSelected()
    {
        // Open the article page.
        if (_selectedItem != null)
        {
            CoreMethods.PushPageModel<GroupArticlePageModel>(_selectedItem, false, true);
        }
     }
    

    _selectedItem 是分配了点击项的属性。 当然,您可以做得更好,并使用CommandParameter 提供行为,您将在其中放置被点击的项目引用。

    【讨论】:

    • 感谢帮助,有道理。
    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2023-03-14
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2020-06-25
    相关资源
    最近更新 更多