简体   繁体   English

具有List的类的C#WPF ViewModel

[英]C# WPF ViewModel for a class with List

I have a class with a list of items, something like this: 我有一堂课,上面列出了一些项目,例如:

public class Model{
    List<int> Items { get; set; }
}

It uses List, not ObservableCollection, and doesn't have any events to be subscribed to. 它使用List,而不是ObservableCollection,并且没有要订阅的任何事件。 I need to make a ListBox oneway-bound to this list and a way to remove items one-by-one. 我需要使ListBox唯一地绑定到此列表,以及一种逐项删除项目的方法。 So I must write a ViewModel class, a property of which can be oneway-bound to ListBox to show these items and to update the ListBox when the list is changed with RemoveItem method. 因此,我必须编写一个ViewModel类,该类的属性可以单向绑定到ListBox,以显示这些项并在使用RemoveItem方法更改列表时更新ListBox。 I don't know how to oneway bind ListBox to this List. 我不知道如何将ListBox绑定到此列表。 If I make a ViewModel class implementing INotifyPropertyChanged the same way I do for string property and a textbox, it doesn't work. 如果我以与对字符串属性和文本框相同的方式制作实现INotifyPropertyChanged的ViewModel类,则它将无法正常工作。 Please teach me how to do this without changing the Model class. 请教我如何执行此操作而不更改Model类。

You could create a property in the view model that is ObservableCollection and initialize it with the list from the model. 您可以在视图模型中创建一个ObservableCollection属性,并使用模型中的列表对其进行初始化。

The view model will implement the 'removeFromList' method where it will remove an item from the ObservableCollection property (the view model's property) and afterwards you will remove the same item from the list in the model. 视图模型将实现'removeFromList'方法,该方法将从ObservableCollection属性(视图模型的属性)中删除一个项目,然后从模型列表中删除相同的项目。

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

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