using System; using System.Collections.Generic; using System.Windows.Controls; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Messaging; using HandyControlDemo.Data; using HandyControlDemo.Service; using HandyControlDemo.Tools; namespace HandyControlDemo.ViewModel { public class MainViewModel : ViewModelBase { #region 字段 /// /// 内容标题 /// private object _contentTitle; /// /// 子内容 /// private object _subContent; /// /// 数据列表 /// private List _dataList; /// /// 当前选中的列表项 /// private ListBoxItem _listBoxItemCurrent; #endregion public MainViewModel(DataService dataService) { Messenger.Default.Register(this, MessageToken.LoadShowContent, obj => { if (SubContent is IDisposable disposable) { disposable.Dispose(); } SubContent = obj; }); Messenger.Default.Register(this, MessageToken.ClearLeftSelected, obj => { if (_listBoxItemCurrent == null) return; _listBoxItemCurrent.IsSelected = false; _listBoxItemCurrent = null; }); DataList = dataService.GetDemoDataList(); } #region 属性 /// /// 数据列表 /// public List DataList { get => _dataList; set => Set(nameof(DataList), ref _dataList, value); } /// /// 子内容 /// public object SubContent { get => _subContent; set => Set(nameof(SubContent), ref _subContent, value); } /// /// 内容标题 /// public object ContentTitle { get => _contentTitle; set => Set(nameof(ContentTitle), ref _contentTitle, value); } #endregion #region 命令 private RelayCommand _switchDemoCmd; /// /// 切换例子命令 /// public RelayCommand SwitchDemoCmd => _switchDemoCmd ?? (_switchDemoCmd = new RelayCommand(SwitchDemo)); #endregion #region 方法 /// /// 切换例子 /// private void SwitchDemo(SelectionChangedEventArgs e) { if (e.AddedItems.Count == 0) return; if (e.AddedItems[0] is ListBoxItem item) { if (item.Tag is string tag) { if (Equals(_listBoxItemCurrent, item)) return; _listBoxItemCurrent = item; ContentTitle = item.Content; Messenger.Default.Send(false, MessageToken.FullSwitch); Messenger.Default.Send(AssemblyHelper.CreateInternalInstance($"UserControl.{tag}"), MessageToken.LoadShowContent); } else { _listBoxItemCurrent = null; ContentTitle = null; SubContent = null; } } } #endregion } }