c# - WPF MVVM : Postpone rendering of View until DataContext is set

标签 c# wpf mvvm datacontext

在我们的 MVVM 应用程序中,在 View 中,DataContext 最初为 null,稍后设置。
View 首先在没有设置 DataContext 的情况下呈现,因此对于绑定(bind),使用默认值或 FallbackValues。一旦设置了 DataContext 并更新了所有绑定(bind),这将导致 UI 发生大量更改。 UI 有点“有弹性”,我可以想象相当多的 CPU 周期被浪费了。
有没有办法在设置 DataContext 之前推迟 View 的渲染?

我们为 ViewModel 查找 View 的代码:

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

最佳答案

是的,你可以这么做

  • 使用 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>
    
  • 关于c# - WPF MVVM : Postpone rendering of View until DataContext is set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39956639/

    相关文章:

    c# - ComboBox 数据源动态变化

    .net - WPF不同的窗口图标和任务栏图标

    c# - 如何在 WPF 应用程序中将 MySQL 表绑定(bind)到数据网格

    c# - Random(int seed) 保证什么?

    C# 文本对齐

    c# - 如何让 View 模型的属性设置所有关联子控件的高度/宽度

    c# - 文本框内容垂直拉伸(stretch)到可用大小

    c# - 如何刷新ViewModel来更新View

    MVVM 中的 WPF 数据绑定(bind) Image.Source

    c# - 在 XAML 页面级别定义的 UserControl DataContext