2011-05-30 26 views
3

爲什麼我無法在設計時解析ContentControl ContentTemplateSelector?
(在它工作的運行時間)
設計師(VS2010)顯示異常:如何在設計時解析ContentControl ContentTemplateSelector?

System.Reflection.TargetInvocationException 異常已被調用的 目標拋出。

System.NullReferenceException對象 參考不設置到 對象的實例。

XAML:

<Window.Resources> 
    <DataTemplate x:Key="Temp1"> 
     <TextBox TextWrapping="Wrap" Text="1" Height="20" Width="Auto"/> 
    </DataTemplate> 

    <local:TemplateSelector x:Key="mySelector"/> 
    <Grid> 
     <ContentControl ContentTemplateSelector="{StaticResource mySelector}"> 
      <ContentControl.Content> 
       1 
      </ContentControl.Content> 
     </ContentControl>  
    </Grid> 
</Window.Resources> 

C#:

public class TemplateSelector : DataTemplateSelector 
    { 
     public override DataTemplate SelectTemplate(object item, DependencyObject container) 
     { 
      //int num = int.Parse(item.ToString()); 
      Window win = Application.Current.MainWindow; 
      return win.FindResource("Temp1") as DataTemplate;//load template based on num... 
     } 

    } 
+0

你的類真的叫'myTemplateSelector'嗎?這與XAML不匹配。 – 2011-05-30 17:03:40

+0

調用沒問題,這是拼寫錯誤。 (如果它在運行時工作,這意味着它沒問題) – 2011-05-30 17:25:14

+0

你應該仍然編輯你的問題,雖然... – 2011-05-30 17:26:27

回答

2

H.B.在設計時約Application.Current.MainWindownull。這裏有一個更好的方式通過名稱檢索資源:

public override DataTemplate SelectTemplate(object item, DependencyObject container) { 
    var element = container as FrameworkElement; 
    if (element != null) { 
     var template = element.TryFindResource("Temp1") as DataTemplate; 
     if (template != null) { 
      return template; 
     } 
    } 
    return base.SelectTemplate(item, container); 
} 

你的代碼的其他部分仍然是不完整的,雖然如此,我希望你只是在它的中間。例如,您的DataTemplate應具有綁定,而不是硬編碼的值。

+0

好吧,這是一個例子,ContentControl將在datagrid的columnheader風格內,它會爲每個列標題加載特定的模板(根據標題名稱) – 2011-05-30 17:35:15

0

我懷疑Application.Current.MainWindow是不是在設計時設置。