2017-04-05 59 views
0

拍了拍我有一個簡單Xamarin.Forms.ContentPage,在一個ListView顯示菜單項:背後Xamarin.Forms.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值。

請注意,我正在嘗試在此處執行「純」MVVM。這意味着我知道我不應該使用事件,並且將代碼留下幾乎空白。但我無法弄清楚如何在這種情況下使用命令。

任何想法/建議如何實現這一目標?

+1

相信e.Item會給您從列表,從中可以得到這兩個鍵和值 – Jason

+0

@Jason數據綁定物品:非常感謝你!現在看起來很明顯... ...!我仍然懷疑是否有可能以任何方式直接「輕鬆」映射命令,但這肯定會實現。再次感謝您的快速反饋:)! –

+0

有點偏離主題:不知道你是否將Listview放入ScrollView只是爲了演示,否則請看看這裏https://stackoverflow.com/questions/6210895/listview-inside-scrollview-is-not-scrolling-on- android/6211286#6211286 – K232

回答

1

將TapGesture添加到ViewCell內容並將命令與它綁定。 例如:

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

在你的情況,你可以直接綁定命令到TextCell。

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

如何在ContentPage上接收命令參數? –