gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:34:11 25 4
gpt4 key购买 nike

在我们的 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com