2016-10-10 13 views
1

MVVMアプリケーションでは、ViewでDataContextは最初はnullであり、後で設定されます。 ビューは最初にDataContextを設定せずにレンダリングされるため、バインディングの場合はデフォルトまたはFallbackValuesが使用されます。これにより、DataContextが設定され、すべてのバインディングが更新されると、UIの変更が多く発生します。 UIは少し「弾力があります」、かなりのCPUサイクルが浪費されていることをイメージすることができます。 DataContextが設定されるまでビューのレンダリングを延期する方法はありますか?WPF MVVM:DataContextが設定されるまで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; 
    } 
+0

たぶんコンテキストがnullでないときに表示するコンバーターをコンテキストに可視性をバインドしますか? –

+0

ありがとう、それは素敵で簡単な解決策です:) – eriksmith200

答えて

1

はい、あなたはFrameworkElement.DataContextChangedイベントを使用して

  1. ことを行うことができます。

  2. 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> 
    
関連する問題