我找到了一个将Catel与TreeView here一起使用的示例,但遗憾的是这个示例是基于Catel版本3.3构建的,我试图在Catel 4.0版本上重复它,但不幸的是它没有用。
当我尝试将我的项目(基于Catel 4.0版)绑定到类TreeViewItemToDataContext中的属性时,缺少对UserControl中ViewModel的引用。
但该示例基于3.3版,一切正常。我想使用IViewModelManager手动获取链接,但遗憾的是在版本4中,版本3.3中没有生成viewModel,一切正常。
问我如何在Catel 4.0版上运行该示例? 附: My test App
更新
public class TreeViewItemToDataContext : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var uc = value as Catel.Windows.Controls.UserControl;
if (uc != null)
{
uc.ViewModelChanged += this.OnViewModelChanged;
return uc.DataContext;
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
private void OnViewModelChanged(object sender, EventArgs eventArgs)
{
var uc = sender as Catel.Windows.Controls.UserControl;
if (uc != null)
{
var visualParent = uc.TemplatedParent as ContentPresenter;
if (visualParent != null)
{
var treeViewItem = visualParent.TemplatedParent as TreeViewItem;
if (treeViewItem != null)
{
var IsSelectedBinding = new Binding("IsSelected");
IsSelectedBinding.Mode = BindingMode.TwoWay;
IsSelectedBinding.Source = uc.ViewModel;
treeViewItem.SetBinding(TreeViewItem.IsSelectedProperty, IsSelectedBinding);
var IsExpandedBinding = new Binding("IsExpanded");
IsExpandedBinding.Mode = BindingMode.TwoWay;
IsExpandedBinding.Source = uc.ViewModel;
treeViewItem.SetBinding(TreeViewItem.IsExpandedProperty, IsExpandedBinding);
uc.ViewModelChanged -= this.OnViewModelChanged;
}
}
}
}
}
ExpandCommand
private void OnSetFocusAndExpandCommandExecute()
{
var model = this.ProviderGroups[0]; // open First Level
var viewModelManager = this.GetServiceLocator().ResolveType<IViewModelManager>();
var viewModels = viewModelManager.GetViewModelsOfModel(model);
if (viewModels.Length > 0)
{
// NOTE: Somehow there are two viewmodels per model
var viewModel = viewModels[0] as TreeViewItemViewModel;
if (viewModel != null)
{
//viewModel.IsSelected = true;
viewModel.IsExpanded = true;
}
}
var model1 = this.ProviderGroups[0].Categories.First(); // open Second Level
var viewModels1 = viewModelManager.GetViewModelsOfModel(model1); // ViewModel Not created.
if (viewModels1.Length > 0)
{
// NOTE: Somehow there are two viewmodels per model
var viewModel1 = viewModels1[0] as TreeViewItemViewModel;
if (viewModel1 != null)
{
viewModel1.IsSelected = true;
viewModel1.IsExpanded = true;
}
}
}
答案 0 :(得分:0)
Catel中的视图模型现在加载时,实际上只需要它们(延迟加载)而不是急切加载。如果您覆盖用户控件上的 OnViewModelChanged ,您将看到它稍后被设置。
您可以订阅转换后的ViewModelChanged事件并等待第一个事件(不要忘记取消订阅)。