如何在MainWindows.xaml.cs

时间:2019-06-28 12:04:11

标签: c# wpf xaml mvvm

我再次在MVVM上苦苦挣扎。我已经阅读了一些教程,但是我的问题仍然存在...

我正在尝试在项目中使用MVVM,并且需要在MainWindows.xaml.cs中使用我的ObservableCollection(在ViewModel中创建)。

我有一个Modell:

public class MvItems : INotifyPropertyChanged
{
    private string mvName;
    public string MvName
    {
        get { return mvName; }
        set
        {
            mvName = value;
            OnPropertyChanged(nameof(MvName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

还有一个ViewModel:

public class MVViewModel
{
    public ObservableCollection<MvItems> Mailverteiler { get { return _Mailverteiler; } }
    public ObservableCollection<MvItems> _Mailverteiler = new ObservableCollection<MvItems>();

    public void LoadMv()
    {
        ObservableCollection<MvItems> temp = new ObservableCollection<MvItems>();

        temp.Add(new MvItems { MvName = "ASD" });
        temp.Add(new MvItems { MvName = "BLA" });
        temp.Add(new MvItems { MvName = "MUH" });

        _Mailverteiler = temp;
    }
}

查看:                                                                                                                                                                                                                                                                                 现在,我可以通过

从MainWindows.xaml.cs添加数据
zTiredV2.ViewModel.MVViewModel MVObject = new zTiredV2.ViewModel.MVViewModel();
MVObject.LoadMv();

lvMailverteiler.DataContext = MVObject;

然后我看到“ ASD”,“ BLA”和“ MUH”。但是,当我按下另一个按钮时,现在如何访问它们?

需要这样的东西:

foreach (MvItems mvitem in Mailverteiler)
{
    if (mvitem.IsChecked == true)
    {
        await this.ShowMessageAsync("Mailverteiler", mvitem.MvName, MessageDialogStyle.Affirmative);
    }
}

又如何将1个项目添加到列表中?

1 个答案:

答案 0 :(得分:0)

好吧,它非常简单...我可以使用

public zTiredV2.ViewModel.MVViewModel MVList = new zTiredV2.ViewModel.MVViewModel();

所以我可以添加项目,遍历它们等等...