簡體   English   中英

Mvvmcross xamarin 在 Listview 模板中形成按鈕命令

[英]Mvvmcross xamarin forms button command inside Listview template

我有視圖模型和視圖,它在 ListView 中列出了我的模型對象,每個列表條目都包含 2 個按鈕:詳細信息和保留。

看法


    <ListView
            ItemsSource="{Binding Models}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackLayout>
                    <Button Command="{Binding Delete}"></Button>
                    <Button Command="{Binding Details}"></Button>
                </StackLayout>
              
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

視圖模型

   class ModelsViewModel : MvxViewModel
    {
        private ObservableCollection<Model> models;
        public ObservableCollection<Model> Models
        {
            get
            {
                return models;
            }
            set
            {
                SetProperty(ref models, value);
            }
        }

        private IMvxCommand details;
        public IMvxCommand Details
        {
            get
            {
                details = details ?? new MvxCommand<ListItem>(o =>
                {

                });
                return details;
            }
        }

        private IMvxCommand delete;
        public IMvxCommand Delete
        {
            get
            {
                delete = delete ?? new MvxCommand<ListItem>(o =>
                {

                });
                return delete;
            }
        }
    }

每個按鈕都應該在 ModelsViewModel 的 Details/Delete 方法中調用 lambda。

但是會發生什么是 listview 中的數據綁定指向不存在此類方法的 Model 對象。 我的問題是,有沒有辦法更改列表視圖中項目的綁定上下文,並將單擊的項目作為參數傳遞?

我嘗試弄亂 Source 並設置 BindingContext 沒有成功

像這樣嘗試:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Name="parentContePage">

    <ListView ItemsSource="{Binding Models}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackLayout>
                    <Button Command="{Binding Source={x:Reference parentContePage}, Path=BindingContext.Delete}"
                    CommandParameter="{Binding .}"/>
                    <Button Command="{Binding Source={x:Reference parentContePage}, Path=BindingContext.Details}"
                    CommandParameter="{Binding .}"/>
                </StackLayout>                
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

確保將x:Name給您的父內容頁面,如上所述。

首先,我可以發表評論,所以我會發布一個答案。 嘗試將命令從MvxCommand<ListItem>更改為MvxCommand<Model> ,因為命令參數在遵循上一個答案后采用了當前模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM