首页 > 解决方案 > 如何通过 viewmodel 中的 mvvm 通过 selecteditem 将 listview 中的数据显示到 xamarin 中的条目?

问题描述

我正在通过 xamarin 中的 SQLite 进行 crud 操作,但我想显示从 listview 到条目的数据,以便我可以更新它,但我不知道如何调用在 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");

    }

标签: c#xamarinxamarin.forms

解决方案


如果您在 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);

    }

推荐阅读