用参数点击的Xamarin.Forms.ListView项

时间:2017-04-05 21:12:11

标签: c# xaml listview mvvm xamarin.forms

我有一个简单的Xamarin.Forms.ContentPage,显示ListView中的菜单项:

<ContentPage x:Class="Mob.Views.Public.MenuPage" ... >
  <ScrollView>
        <ListView ItemsSource="{Binding MenuItems}" ItemTapped="{Binding OnMenuItemTapped}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Key}" />
                    <!-- How to pass the "{Binding Value}" to OnMenuItemTapped? -->
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
  </ScrollView>
</ContentPage>

代码背后:

public class MenuPage : ContentPage
{
    public MenuPage()
    {
        InitializeComponent();
        BindingContext = new MenuViewModel(); 
    }
    private async void OnMenuItemTapped(object sender, ItemTappedEventArgs e)
    {
        await (this.BindingContext as MenuViewModel).OnMenuItemTappedAsync(/* MUST PASS THE VALUE HERE*/);
    }
}

如您所见,ItemsSource绑定到ViewModel的MenuItems属性。此属性的类型为Dictionnary<string, string>Key用于显示项目的文本,而Value应作为参数传递给OnMenuItemTapped事件。

class MenuViewModel : ViewModelBase
{
    ...
    public IDictionary<string, string> MenuItems { get { return _menuItems; } set { SetProperty(ref _menuItems, value); } }
    // public ICommand OnMenuItemTappedCommand { get; set; }
    public MenuViewModel()
    {
        MenuItems = new Dictionary<string, string>();
        MenuItems.Add("XXX", "PageX");
        MenuItems.Add("YYY", "PageY");
        MenuItems.Add("ZZZ", "PageZ");
        // ...
        // I would've prefere to bind the item tap using a command but I can't figure out how to
        // OnMenuItemTappedCommand = new Command<string>(OnMenuItemTappedAsync);
    }

    public async Task OnMenuItemTappedAsync(string targetPage)
    {
        // await Navigation.PushModalAsync(...);
        // --> depending on the targetPage
    }
}

我的目标是根据传递给OnMenuItemTappedAsync的值导航到正确的页面。

注意,我正在努力做到&#34;纯粹&#34; MVVM在这里。意思是我知道我不应该使用事件并将代码留下几乎为空。但我无法弄清楚如何在这种情况下使用命令。

任何想法/建议如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

将TapGesture添加到ViewCell内容并将Command与其绑定。 例如:

<TapGestureRecognizer Command="{Binding OnMenuItemTappedCommand}" CommandParameter="{Binding .}" />

在您的情况下,您可以将命令直接绑定到TextCell。

<TextCell Command="{Binding OnMenuItemTappedCommand}" CommandParameter="{Binding .}">