c# - 如何通过 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");
}
解决方案
如果您在 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);
}
推荐阅读
- magento - Groovy - 序列化 XML NodeChildren
- c++ - 如何在多维数组/网格 C++ 中创建列表
- java - Jboss 和 Hotswap Agent 使用 Jboss 模块
- ruby-on-rails - 针对 Devise 身份验证对多个 Rails 服务器进行身份验证
- c# - 在 LINQ 中按列表分组
- javascript - 将变量公开给 javascript 上下文 (Java / WebView)
- cmake - 生成依赖于外部资源的仅标头库的 .lib
- java - REST API 方法获取
- ios - 滚动collectionview时CircularProgressBar颜色变化
- sql - PostgreSQL 在函数中获得最新记录