繁体   English   中英

如何通过视图模型中的 mvvm 通过 selecteditem 显示从列表视图到 xamarin 中的条目的数据?

[英]how to show data from listview to entry in xamarin by selecteditem through mvvm in viewmodel?

我正在通过 xamarin 中的 SQLite 进行 crud 操作,但我想显示从列表视图到条目的数据,以便我可以更新它,但我不知道如何调用在 xaml 中绑定的选定项目

    <ListView  ItemsSource="{Binding companylist}" SelectedItem="{Binding selectedname}" >
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Label Text="{Binding name}"/>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <StackLayout>

        <Entry Text="{Binding id}" IsVisible="False"/>
        <Entry Placeholder="Name" Text="{Binding name}"/>
        <Button Text="Update" Command="{Binding UpdateCompanyCommand}"/>
    </StackLayout>
</StackLayout>

视图模型中的代码是

 public Command UpdateCompanyCommand { get; }
    async Task UpdateCompany()
    {
        var db = new SQLiteConnection(dbpath);
        Company company = new Company()
        {
            id=id,

            name = Name


        };
        db.Update(company);
        await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Message", "Name is Updated", "Ok");

    }

如果您在 ListView 中选择一个新项目,将触发ItemSelected ,然后您可以执行以下步骤来更新 UI 和 DB:

    ...
    this.BindingContext = ViewModel;
    ...

    private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        //1.get the selected model, get the selected name
        Company item = e.SelectedItem as Company;
        string selectedName = item.name;

        //2.update the name property in the model you bind to the entry.
        ViewModel.name = selectedName;

        //3. call UpdateCompany
        ...
        db.Update(item);

    }

您可以通过将您的名称属性绑定到带有 ListView 的 SelectedItem 的条目来实现它,如下所示,

<Entry Text="{Binding name}" 
       BindingContext="{Binding SelectedItem, Source={x:Reference listView}}" />

为 ListView 命名,并根据您选择的项目设置 Entry 的 BindingContext。 只要列表视图选择的项目发生变化,条目就会更新。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM