我最终使用了带有 ViewModel 缓存的 ValueConverter。它实际上工作得很好。我像这样设置我的 TreeView:
<TreeView ItemsSource="{Binding TreeRoot}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<ContentPresenter Content="{Binding Converter={StaticResource ModelToViewModelConverter}}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
...其中 TreeRoot 是模型对象树的根,每个对象都有一个属性“Children”。并像这样创建了我的转换器:
public class ModelToViewModelConverter : IValueConverter
{
private static Dictionary<Guid, ViewModelBase> _map = new Dictionary<Guid, ViewModelBase>();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var element = value as ElementBase;
if (!_map.ContainsKey(element.Id))
{
if (element is ElementSet)_map.Add(element.Id, new ElementSetViewModel(value as ElementSet));
if (element is ElementGroup) _map.Add(element.Id, new ElementGroupViewModel(value as ElementGroup));
if (element is StringElement) _map.Add(element.Id, new StringElementViewModel(value as StringElement));
if (element is ScalarElement) _map.Add(element.Id, new ScalarElementViewModel(value as ScalarElement));
}
return _map[element.Id];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
//A change.sdfsdfdsff
throw new NotImplementedException();
}
}
这允许我只维护一棵模型对象树,但允许我使用 ViewModels 来绑定视图。