【问题标题】:Bind ViewModel List<T> to Listbox in C# Windows Universal App将 ViewModel List<T> 绑定到 C# Windows 通用应用程序中的列表框
【发布时间】:2015-05-21 22:49:34
【问题描述】:

我有一个列表框,我希望在将项目添加到列表时对其进行更新。我知道我需要绑定列表框。我试图关注这个question/answer

我有一个处理列表的 ViewModel:

namespace TESTS
{
public class ViewModel : INotifyPropertyChanged
{
    private List<Cars> _listCars;
    public List<Cars> listCars
    {
        get
        {
            return _listCars;
        }

        set
        {
            if (_listCars == value)
            {
                return;
            }

            this.RaisePropertyChanged("Message");
            _listCars = value;
            this.RaisePropertyChanged("Message");
        }
    }
   public ViewModel()
    {
        listCars = new List<Cars>();
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        Debug.WriteLine("Property Changed");
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
}

这是汽车类:

public class Cars: INotifyPropertyChanged
{
    public string model{ get; set; }
    public string year{ get; set; }
    public event PropertyChangedEventHandler PropertyChanged;
}

所以我将列表框绑定到我的 Viewmodel 中的属性路径,即 listCars。

<ListBox .... ItemsSource="{Binding listCars}">

所以当在我的 Main.xaml.cs 中时。我单击按钮并添加项目。即使它绑定到视图模型上的列表,它也不会被添加到列表框。

public sealed partial class MainPage : Page
{
    public static ViewModel vm = new ViewModel();
    public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = vm;            
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        Cars x = new Cars();
        x.model = "Ford";
        x.Year = "1998";
        vm.listCars.Add(x);
    }
}

我希望我能很好地解释我实施的内容。我的 ViewModel 实现有问题吗?我是 MVVM 的新手。请帮忙。

【问题讨论】:

  • 只要使用ObservableCollection&lt;T&gt;,它就会解决你所有的问题。
  • 但是 List 不可能吗?

标签: c# xaml mvvm listbox windows-store-apps


【解决方案1】:
  1. 使用ObservableCollection&lt;T&gt;,而不是List&lt;T&gt;。前者被设计为与 MVVM 一起使用,后者不是。您将自动收到所有通知。使用List&lt;T&gt; 是可行的,但是您必须编写更多代码并且性能会很多 更差,尤其是在大集合的情况下。只是不要这样做。

  2. 如果您在构造函数中创建集合,将其分配给只读属性并且从不更改其实例(这是您应该这样做的方式),您甚至不需要实现 INPC。

  3. 在实现 INPC 时,您应该在更改属性一次后调用 RaisePropertyChanged,并且使用已更改的属性名称,而不是随机不相关的字符串。

【讨论】:

  • 是的,它成功了!感谢您提供的信息.. :)。我会使用 ObservableCollection 。我在使用它时有点犹豫,因为我不知道如何在其中搜索元素,但会对此进行研究..
  • 不是随机不相关的字符串。面相见掌
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多