我有一些样式文件。
例如ButtonStyles.xaml如下所示:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style
x:Key="CustomButtonStyle"
TargetType="Button">
<Setter
Property="Foreground"
Value="White" />
<Setter
Property="Background"
Value="Black" />
<Setter
Property="Height"
Value="32" />
</Style>
<Style
TargetType="Button"
BasedOn="{StaticResource CustomButtonStyle}">
</Style>
</ResourceDictionary>
我有从我的BasePage扩展的页面。 如果我希望我的新样式覆盖控件,我必须在每个页面中添加此代码:
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Styles/ButtonStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
但是如果我在我的BasePage中有这个代码,它就不会成为我的控件的主题。
有没有办法在每个页面中导入我的样式而不会反复粘贴这些代码?
答案 0 :(得分:1)
我无法在我身边使用 <asp:TreeView ID="navTree" runat="server" NodeIndent="0" ShowExpandCollapse="false">
重现此问题。如果您可以发布可以重现您的问题的样本会更好。
但是,要在每个页面中使用自定义样式,我建议将资源字典合并到BasePage
中。 Application.Resources
是放置应用导航结构中多个网页引用的特定应用资源的最佳位置。如果在Application.Resources
中找不到请求的资源,则XAML资源系统将尝试检查Page.Resources
属性。因此,如果我们将资源字典合并到Application.Resources
,我们可以在应用的所有页面中使用它们。如果我们想在某些网页中使用某些不同的样式,我们可以在Application.Resources
中指定新的Style
。有关详细信息,请参阅Lookup behavior for XAML resource references。
因此我们可以将资源词典合并到Page.Resources
中,如下所示:
(请注意,Application.Resources
不能在WinRT XAML中使用,我们应该使用“/”来引用包根。)
../Styles/ButtonStyles.xaml
然后在其他页面中,如果我们没有为<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Styles/ButtonStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
指定Style
,它将使用ButtonStyles.xaml中定义的样式。