2016-10-10 82 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>