簡體   English   中英

綁定ViewModel列表 <T> 到C#Windows Universal App中的列表框

[英]Bind ViewModel List<T> to Listbox in C# Windows Universal App

我有一個列表框,我希望在項目添加到列表時更新。 我知道我需要綁定列表框。 我試圖按照這個問題/答案

我有一個處理列表的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;
}

所以我將listbox綁定到我的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的新手。 請幫忙。

  1. 使用ObservableCollection<T> ,而不是List<T> 前者旨在與MVVM一起使用,后者則不然。 您將自動收到所有通知。 它可以使用List<T> ,但你必須編寫更多的代碼,性能會差,尤其是對於大型集合。 只是不要這樣做。

  2. 如果在構造函數中創建集合,將其分配給只讀屬性並且永遠不會更改其實例(這是您應該這樣做的方式),您甚至不需要實現INPC。

  3. 在實現INPC時,您需要在更改屬性一次后調用RaisePropertyChanged ,並使用已更改的屬性名稱,而不是隨機無關的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM