【发布时间】:2019-12-15 15:35:30
【问题描述】:
在我的 Xamarin.Forms 应用程序中,我有一个简单的联系人类 [Model]。在 UI [View] 中存在一个显示联系人的 ListView。在我的模型视图类中,我有一个分配给 ListView 的 itemSource 属性的联系人列表 (_listOfContacts)。这个联系人列表是一个 ObservableCollection。我的问题是当用户从 ContextActions 单击删除时,我可以看到 _listOfContacts 已更新,但 ListView 未更新。 只有当我将它的 itemsource 重新分配给 _listOfContacts 时,ListView 才会更新。如果 _listOfContacts 是联系人的 ObservableCollection,则不需要这样做。 我是 MVVM 的新手,所以在继续学习更高级的技术之前,我需要清除这些基本的 MVVM 概念。 这是我的代码:
型号
class Contact
{
public String Name { get; set; }
public String Status { get; set; }
public String ImageUrl { get; set; }
}
模型视图
public partial class ContactListPage : ContentPage
{
private ObservableCollection<Contact> _listOfContacts;
public ContactListPage()
{
InitializeComponent();
_listOfContacts = new ObservableCollection<Contact>
{
new Contact {Name="Item1", ImageUrl="http://lorempixel.com/100/100/people/1" , Status="Hey"},
new Contact { Name = "Item2", ImageUrl = "http://lorempixel.com/100/100/people/2", Status="Hey" },
};
contactList.ItemsSource = _listOfContacts.ToList();
}
private void EditContactClick(object sender, EventArgs e)
{
DisplayAlert("Alert", "Clicked Edit", "Cancel");
}
private void DeleteContactClick(object sender, EventArgs e)
{
var contact = (sender as MenuItem).CommandParameter as Contact;
_listOfContacts.Remove(contact);
//following line of code should not be needed since _listOfContacts is
//an ObservableCollection and removing an item should update the bound control automatically
**contactList.ItemsSource = _listOfContacts.ToList();**
}
}
查看
<ContentPage.Content>
<StackLayout>
<ListView x:Name="contactList" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" Padding="10">
<Image Source="{Binding ImageUrl}"/>
<StackLayout HorizontalOptions="StartAndExpand">
<Label Text="{Binding Name}" Margin="0,2,0,2"/>
<Label Text="{Binding Status}" Margin="0,2,0,2" />
</StackLayout>
</StackLayout>
<ViewCell.ContextActions>
<MenuItem Text="Edit" Clicked="EditContactClick" CommandParameter="{Binding .}"/>
<MenuItem Text="Delete" Clicked="DeleteContactClick" IsDestructive="True" CommandParameter="{Binding .}"/>
</ViewCell.ContextActions>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
【问题讨论】:
标签: c# listview mvvm xamarin.forms observablecollection