2016-10-10 49 views
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; 
    } 
+0

能见度情况下也许绑定在转换时显示上下文不为空? –

+0

谢谢,这是一个不错的和简单的解决方案:) – eriksmith200

回答

1

是的,你可以做到这一点

  1. 使用FrameworkElement.DataContextChanged事件。使用Trigger

    示意图例如;

    <ContentControl> 
    <ContentControl.Resources> 
        <DataTemplate x:Key="MyTmplKey"> 
         <TextBlock Text="Not null"/> 
        </DataTemplate> 
        <DataTemplate x:Key="DefaultTmplKey"> 
         <StackPanel> 
          <TextBlock Text="null"/> 
          <Button Content="Press" Click="Button_Click_1"/> 
         </StackPanel> 
        </DataTemplate> 
    </ContentControl.Resources> 
    <ContentControl.Style> 
        <Style TargetType="ContentControl"> 
         <Setter Property="ContentTemplate" Value="{StaticResource MyTmplKey}"/> 
         <Style.Triggers> 
          <Trigger Property="DataContext" Value="{x:Null}"> 
           <Setter Property="ContentTemplate" Value="{StaticResource DefaultTmplKey}"/> 
          </Trigger> 
         </Style.Triggers> 
        </Style> 
    </ContentControl.Style> 
    </ContentControl>