MVVM treeview wpf(绑定?)

 mobiledu2502889953 发布于 2023-01-31 18:43

抱歉没有问题.也许这不是一个问题 - 但我需要一个教程样本/我正在尝试编写一个模型任务,以便在wpf中使用mvvm模式获得"方便".我决定写一些像图书管理员的帮手.这是一个简单的wpf窗口,其中包含一个组合框(用于选择书籍是幻想还是sf),文本框(用于书名输入),按钮添加以及树状视图,如下所示:

 Books
  ------>ScienceFic
        ----->bookName1
        ----->bookName2
  ------->Fantasy
        ------>bookName3

我从视图中看绑定和分离视图模型有一些困难.你可以帮帮我吗?

public enum LibraryType
{
    ScienceFic,
    Fantasy
}
    Class Model: INotifyPropertyChanged
    {
     private int bookId;
     private string bookName;
     private LibraryType bookType;
     public event PropertyChangedEventHandler PropertyChanged;
        //....and for all this fields  I have used a INotifyPropertyChanged as 
    /*
    http://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does-a-better-way-exist
    */
    }

在这一点上,我认为MODEL已经完成了.

现在关于VIEW:我只需打开MainWindow的编辑器并手动添加按钮,文本框,组合框和树视图.加入后

comboBox1.ItemsSource = Enum.GetValues(typeof(LibraryType)).Cast();
 comboBox1.SelectedIndex = 0;

我用正确类型的书初始化了我的组合)))但是((我在代码中完成了这个,而不是在XAML中 - 对于MVVM绑定是否正确?(第一个问题)接下来,我有绑定(我认为)我的textBox文本到ViewModel中的当前书名属性(我在XAML中这样做了):

 

这是正确的吗?(第二个问题)

最后,VIEWMODEL

 Class ViewModel
{
  private string currentBookName;
  private LibraryType selectedBookType;
  public event PropertyChangedEventHandler PropertyChanged;
  //also properties and  OnPropertyChanged/SetField functions like in Model class

  //and finally I have created two lists for book storing
  private List sfStorage = new List();
  private List fantasyStorage = new List();
  //and simple getters for this two lists, like:
  public List GetSFStorage
  {
   get{return this.sfStorage;}
  }
  //and a simple function for addition of new books
  //that I plan to call when AddButton pressed
  public void Addition(???)
        {
            if (!string.IsNullOrEmpty(currentBookName))
            {
                //? I have add CurrentBookName in XAML of View (see above)
                //?but is it enough to have a property of CurrentBookType
                //to grant that a valide value from combobox will be here?
                var modelNewBook = new Model(CurrentBookName,CurrentBookType);
                switch (selectedBookType)
                {
                    case LibraryType.ScienceFic:
                        sfStorage.Add(modelNewBook);
                        break;
                    case LibraryType.Fantasy:
                        fantasyStorage.Add(modelNewBook);
                        break;
                    default:
                        return;
                }
            }
}

现在我只是走出成功的一小部分(可能)但是,我如何在xaml或代码中将这两个列表连接到一个树视图中当按下Addbutton时,如何调用Addition函数(第三个和主要问题)?也许,这是noob问题,但我真的需要一个样本.并且,(或许)这个问题对于试图理解MVVM和绑定的其他人有帮助.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有