一、安装
1、nuget搜索“mvvmlight”安装
安装完成安装了如下3个相关插件
mvvmlights和commonservicelocator是自动关联安装的
2、安装时版本不要选最新,否则后期会提示找不到相关引用
如下图,安装4.X版本
3、安装完成后,项目目录下自动生成viewmodel文件夹和viewmodellocator类
viewmodellocator作用在于统一建立所有xaml页面、xaml.cs与viewmodel之间的关系,实现数据/实体的双向绑定,并实例化viewmodel
二、tabcontrol数据绑定实例
1、新增基类ViewModelBase<T>,继承ViewModelBase,封装数据传递实体
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IIViewUI.ViewModel
{
public class ViewModelBase<T> : ViewModelBase
{
/// <summary>
/// 数据列表
/// </summary>
private IList<T> _dataList;
/// <summary>
/// 数据列表
/// </summary>
public IList<T> DataList
{
get => _dataList;
#if netle40
set => Set(nameof(DataList), ref _dataList, value);
#else
set => Set(ref _dataList, value);
#endif
}
}
}
2、新增PIndex page页面
(1)上图标注1与"viewmodel"对应viewmodellocator,其中“PIView”一定要与viewmodellocator中实例化的名称
(2)上图标注2,对应viewmodel对应的实例化的实体名称
(3)上图标注3,对应实体类的属性
3、新增实体类TabControlModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class TabControlModel
{
public string Header { get; set; }
public string Url { get; set; }
}
}
4、新增PIndexViewModel继承ViewModelBase<TabControlModel>
在构造函数中获取数据并封装进DataList
using DTO;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using HandyControl.Data;
using IIViewUI.Pages;
using IIViewUI.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace ViewModel
{
public class PIndexViewModel : ViewModelBase<TabControlModel>
{
public PIndexViewModel()
{
DataList = GetTabControlDemoDataList();
AddTabItemCommand = new RelayCommand(AddTabItem);
}
public RelayCommand AddTabItemCommand { get; set; }
private void AddTabItem()
{
//CreatNewTab("百度一下", "IIViewUI.Pages.PToBeInterviewed");
}
internal ObservableCollection<TabControlModel> GetTabControlDemoDataList()
{
return new ObservableCollection<TabControlModel>
{
new TabControlModel
{
Header = "Success",
Url = "IIViewUI.Pages.PToBeInterviewed"
},
new TabControlModel
{
Header = "Primary",
Url = "IIViewUI.Pages.PToBeInterviewed"
},
new TabControlModel
{
Header = "Warning",
Url = "IIViewUI.Pages.PToBeInterviewed"
},
new TabControlModel
{
Header = "Danger",
Url = "IIViewUI.Pages.PToBeInterviewed"
},
new TabControlModel
{
Header = "Info",
Url = "IIViewUI.Pages.PToBeInterviewed"
}
};
}
}
}