WPF MVVM:延迟呈现视图,直到DataContext设置

本文关键字:直到 DataContext 设置 视图 MVVM 延迟 WPF | 更新日期: 2023-09-27 18:12:34

在我们的MVVM应用程序中,在视图中,DataContext最初为空,稍后再设置。视图第一次呈现时没有DataContext集,因此对于绑定使用默认值或FallbackValues。一旦设置了DataContext并更新了所有绑定,这将导致UI中的许多更改。UI有点"弹性",我可以想象相当多的CPU周期被浪费了。是否有一种方法来推迟渲染视图,直到DataContext设置?

为ViewModel查找视图的代码:

<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;
  }

WPF MVVM:延迟呈现视图,直到DataContext设置

是的,你可以这么做

  1. 使用FrameworkElement.DataContextChanged事件

  2. 使用Trigger

    示意图示例eg;

    <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>