1

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

我在modelPage中将事件绑定到什么?

谢谢,

麦克风

4

1 回答 1

1

因为ItemTapped是一个事件而不是一个Command(或BindableProperty根本没有)你不能直接从你那里使用它PageModel

他们Behaviors为此发明了类似的东西。使用 Behaviors,您可以将 aEvent转换为Command.

虽然有像Corcav 一样的第三方插件,但它现在也内置在Xamarin.Forms中。

让我通过 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。这可能是您想要的,因为否则您点击的项目将保持选中状态。因此,该属性除了将其设置回(因此是 TwoWay)外,SelectedItem并没有做更多的事情。null但您也可以从那里获取实际选定的项目。

因此,现在在您PageModel声明一个命令并为其分配如下内容:

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

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

于 2016-06-21T07:50:19.090 回答