2014-10-29 21 views
0

我試圖讓這個例子工作。我創建了一個新的WPF自定義控件庫項目,並在Generic.xaml我有以下代碼ContentControl不拾取模板,雖然DynamicResource

<ResourceDictionary 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="clr-namespace:WpfCustomControlLibrary1"> 

<ControlTemplate x:Key="myControlTemplate1"> 
    <TextBlock Text="This text should appear"></TextBlock> 
</ControlTemplate> 
<Style TargetType="{x:Type local:CustomControl1}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type local:CustomControl1}"> 
       <Border Background="{TemplateBinding Background}" 
         BorderBrush="{TemplateBinding BorderBrush}" 
         BorderThickness="{TemplateBinding BorderThickness}"> 

        <ContentControl Template="{DynamicResource myControlTemplate1}"></ContentControl> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

當我使用我的控制中的應用程序,我沒有看到TextBlock。爲什麼?

但是,如果我改變它使用模板作爲StaticResource,它的工作原理。爲什麼?

+0

[WPF StaticResource有效,DynamicResource不可以]的重複(http://stackoverflow.com/questions/3537107/wpf-staticresource-works-dynamicresource-doesnt) – fahadash 2014-10-29 05:44:47

回答

0

我想答案是here(最後一句在下面的文字):

靜態資源查找可以延伸到主題,或進入系統資源,但由於XAML裝載機推遲了,這是唯一支持請求。推遲是必要的,以便頁面加載時的運行時主題適用於應用程序。但是,不推薦對已知僅存在於主題或系統資源中的密鑰進行靜態資源引用。這是因爲如果用戶實時更改主題,則不會重新評估這些引用。當您請求主題或系統資源時,動態資源引用更可靠。例外情況是主題元素本身請求另一個資源。由於前面提到的原因,這些引用應該是靜態資源引用。

雖然您可以將Generic.xaml合併到您的應用程序資源中,然後資源查找不會擴展到主題中。