2

也許有人會幫助我。我一直在試圖找到一種解決方案,以在我的WindowsPhone項目上共享樣式和資源。跨程序集的合併詞典和共享樣式

存在的問題如下:

我有其中使用由兩個WP項目共同的組件。在這個程序集裏​​面我定義了一些樣式和數據模板。我希望在普通程序集中定義其中一個數據模板,並將其作爲項目的默認數據模板。

大會資源字典的示例代碼:

<Style TargetType="TextBlock" x:Key="TopItemsTitle"> 
    <Setter Property="FontSize" Value="18"></Setter> 
    <Setter Property="FontFamily" Value="Segoe WP Black"></Setter> 
    <Setter Property="Foreground" Value="Red"></Setter> 
</Style> 

<DataTemplate x:Key="TopItemsTemplate"> 
    <Button> 
     <TextBlock x:Name="Name" 
        Grid.Row="1" 
        Width="172" 
        Height="25" 
        Margin="0,6,0,50" 
        VerticalAlignment="Bottom" 
        Text="{Binding Name}" 
        TextWrapping="Wrap" 
        Style="{StaticResource TopItemsTitle}" /> 
    </Button> 
</DataTemplate> 

內不同項目,我想重新定義TopItemsTitle風格,例如:

<Style TargetType="TextBlock" x:Key="TopItemsTitle"> 
    <Setter Property="FontSize" Value="20"></Setter> 
    <Setter Property="FontFamily" Value="Segoe WP"></Setter> 
    <Setter Property="Foreground" Value="Blue"></Setter> 
</Style> 

然後合併在應用這兩個資源字典。一個WP項目的xaml:

<ResourceDictionary> 
    <ResourceDictionary.MergedDictionaries> 
     <ResourceDictionary Source="/Assembly;component/Resources/Style.xaml" /> 
     <ResourceDictionary Source="Resources/LocalStyle.xaml" /> 
    </ResourceDictionary.MergedDictionaries> 
</ResourceDictionary> 

根據到MSDN這應該是可以的。但實際上這是行不通的。數據模板不反映重新定義的樣式並使用默認樣式。

這是一個錯誤還是我簡單做錯了?

任何形式的幫助將不勝感激。

回答

0

我想你是誤解了這篇文章。查找StaticResource總是從元素開始,然後向上走。

TopItemsTemplate在共用Style.xaml定義的,因此在模板任何{StaticResource}參考將首先查找在Button匹配(無發現),則DataTemplate(無找到),那麼Style.xamlResourceDictionary(實測值)。如果在Style.xaml中找不到任何內容,那麼只有這樣纔會繼續嘗試在合併的字典中找到一個。

如果您將TopItemsTitle移動到不同的字典(所以合併的字典有3個來源而不是2),它可能會工作,但我不是100%確定。

+0

謝謝@RobSiklos,您正確地將TopItemsTitle風格移到不同的字典中來解決問題。 其實我發現了別的東西,你不需要在通用的style.xaml字典上定義樣式,你可以在它們各自的LocalStyle.xaml字典上爲每個應用程序在本地定義它。 – Mike 2013-03-27 14:46:22