要实现这样一个功能,我之前是采用传统方式实现的,本节我采用CM框架下的Conductor<T>去实现,这样代码量可以大幅度压缩,核心代码就一行。
后台代码:
①定义集合并添加数据:
public IViewModel ActiveWindowView { get; set; }
public ObservableCollection<string> ListBoxItems { get; set; }
public string SelectedItem { get; set; }
ListBoxItems = new ObservableCollection<string>() { };
ListBoxItems.Add("ShellView");
ListBoxItems.Add("EventAggregatorView");
ListBoxItems.Add("ConductorView");
ListBoxItems.Add("MatchTemplateView");
ListBoxItems.Add("IndicatorLightView");
ListBoxItems.Add("MemorandumView");
ListBoxItems.Add("FTPTestView");
②listbox选择改变后切换页面:
public void ListBoxItems_SelectionChanged()
{
switch(SelectedItem)
{
case "ShellView":
ActiveWindowView = new ShellViewModel();break;
case "EventAggregatorView":
ActiveWindowView = EventAggregatorViewModel.Instance; break;
case "ConductorView":
ActiveWindowView = new ConductorViewModel(); break;
case "MatchTemplateView":
ActiveWindowView = new MatchTemplateViewModel(); break;
case "IndicatorLightView":
ActiveWindowView = new IndicatorLightViewModel(); break;
case "MemorandumView":
ActiveWindowView = IoC.Get<MemorandumViewModel>(); break;
case "FTPTestView":
ActiveWindowView = new FTPTestViewModel(new FTPConfig()); break;
default:break;
}
}
③前台绑定:
<ListBox Name="ListBoxItems" Grid.Column="0" SelectedItem="{Binding SelectedItem}" Margin="2"
cal:Message.Attach="[Event SelectionChanged] = [Action ListBoxItems_SelectionChanged]"/>
<ContentControl Name="ActiveWindowView"/>
① 后台代码:
首先是需要继承Conductor<IViewModel>.Collection.OneActive这样才能使用这个类下面的方法和属性,其次是构造函数需要添加接收的接口
IEnumerable<T>,这样改造完代码如下:
public MainWindowViewModel(IEnumerable<IViewModel> modules)
{
Items.AddRange(modules);
ActivateItem(Items.FirstOrDefault(vm => vm.GetType() ==typeof(IndicatorLightViewModel)));
}
如果不考虑首次激活的页面那核心代码就只有一句:
Items.AddRange(modules);
②前台代码:
<ListBox Name="Items" Grid.Column="0" Margin="2" DisplayMemberPath="DisplayName"/>
<ContentControl Name="ActiveItem"/>
这样前后台就设置完事了,继承了一个框架的多屏幕管理类,使得前后台代码大幅度精简,功能上也没打折扣,准确说是更强大了,这就是CM框架的优势所在。
百度网盘链接:https://pan.baidu.com/s/1Qvi2LKHX_OpjDvvvcrijgw