1
在我们的MVVM应用程序中,在View中,DataContext最初为空,稍后进行设置。 视图首先在没有DataContext集的情况下呈现,因此对于绑定使用默认或FallbackValues。一旦设置了DataContext并更新了所有绑定,这会导致UI中发生很多更改。用户界面有点“有弹性”,我可以成像几个CPU周期的浪费。 有没有办法推迟视图呈现,直到DataContext设置?WPF MVVM:推迟渲染视图直到设置DataContext
我们的代码,以找到一个视图模型视图:
<ContentControl
DataContext="{Binding Viewodel}"
Content="{Binding}"
Template="{Binding Converter={converters:ViewModelToViewConverter}}"/>
ViewModelToViewConverter.cs:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ViewModel viewModel = value as ViewModel;
if (viewModel == null)
{
return null;
}
string modelName = viewModel.ToString();
string mappingId = viewModel.MappingId;
if (!string.IsNullOrEmpty(mappingId))
{
modelName += "_" + mappingId;
}
ControlTemplate controlTemplate = new ControlTemplate();
MappingEntry mappingEntry = ApplicationStore.SystemConfig.GetMappingEntryOnModelName(modelName); // lookup View definition for ViewModel
Type type = mappingEntry != null ? mappingEntry.ViewType : null;
if (type != null)
{
controlTemplate.VisualTree = new FrameworkElementFactory(type);
}
else
{
Logger.ErrorFormat("View not found: {0}", modelName);
}
return controlTemplate;
}
能见度情况下也许绑定在转换时显示上下文不为空? –
谢谢,这是一个不错的和简单的解决方案:) – eriksmith200