具有List的类的C#WPF ViewModel [英] C# WPF ViewModel for a class with List

查看:124
本文介绍了具有List的类的C#WPF ViewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课,上面有一系列的项目,像这样:

I have a class with a list of items, something like this:

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

它使用List,而不是ObservableCollection,并且没有要订阅的任何事件. 我需要使ListBox唯一地绑定到此列表,以及一种逐项删除项目的方法.因此,我必须编写一个ViewModel类,该类的属性可以单向绑定到ListBox,以显示这些项并在使用RemoveItem方法更改列表时更新ListBox.我不知道如何将ListBox绑定到此列表.如果我以与对字符串属性和文本框相同的方式制作实现INotifyPropertyChanged的ViewModel类,则它将无法正常工作. 请教我如何在不更改Model类的情况下执行此操作.

It uses List, not ObservableCollection, and doesn't have any events to be subscribed to. I need to make a ListBox oneway-bound to this list and a way to remove items one-by-one. 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. I don't know how to oneway bind ListBox to this List. If I make a ViewModel class implementing INotifyPropertyChanged the same way I do for string property and a textbox, it doesn't work. Please teach me how to do this without changing the Model class.

推荐答案

您可以在视图模型中创建一个ObservableCollection属性,并使用该模型中的列表对其进行初始化.

You could create a property in the view model that is ObservableCollection and initialize it with the list from the model.

视图模型将实现'removeFromList'方法,该方法将从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.

这篇关于具有List的类的C#WPF ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆