【发布时间】:2016-03-01 22:30:18
【问题描述】:
我一直在做一些 WPF 项目,但我大部分时间都远离模板和资源字典,因为它们是一个集群#。为了更上一层楼,我做了很多谷歌搜索,试图找到使用资源字典等应用样式的最佳实践,但似乎最佳实践是基于习惯和偏好的。我遇到的大多数示例要么假设您已经了解所有内容,要么不包括所有不同的情况。最糟糕的是,有一些已知的错误和情况会影响性能,但了解这些问题是什么并纠正它们本身就是另一个麻烦。
对不起,你的咆哮。以下是我需要解决的情况:
假设我有一个默认的 rd(资源字典),它具有针对文本块、按钮、文本框等的样式。然后,我有另一个类似的资源字典,它适用于像 Expander(或 TabItem)这样的东西,它是那些的集合相同的控件(按钮、文本框、...)。
这样的设置可以吗?
如何覆盖位于特定扩展器内的控件的默认 rd?我尝试在扩展器的资源中添加对资源字典的引用;但是,默认 rd 似乎覆盖了该样式。
模板的用途是什么?您什么时候使用这些模板?
这是我目前的设置:
App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/rdMainStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
rdMainStyle.xaml:
<Style x:Key="baseStyle" TargetType="FrameworkElement">
<Setter Property="Width" Value="Auto"/>
<Setter Property="Height" Value="Auto"/>
<Setter Property="MinWidth" Value="70pt"/>
</Style>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource baseStyle}">
<Setter Property="Margin" Value="5, 0, 0, 5"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource baseStyle}">
<Setter Property="MinWidth" Value="65pt"/>
<Setter Property="Margin" Value="5, 0, 0, 5"/>
</Style>
rdExpanderStyle.xaml:
<Style x:Key="expanderBaseStyle" TargetType="FrameworkElement">
<Setter Property="Height" Value="Auto"/>
<Setter Property="Margin" Value="5, 0, 0, 5"/>
</Style>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource expanderBaseStyle}">
<Setter Property="Width" Value="70pt"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource expanderBaseStyle}">
<Setter Property="Width" Value="65pt"/>
</Style>
主窗口内:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Expander Grid.Row="0" Name="expSync" Header="More Options">
<Expander.Resources>
<ResourceDictionary Source="Resources/rdExpanderStyle.xaml" />
</Expander.Resources>
</Expander>
<StackPanel Margin="0,5,0,0">
<TextBlock Text="bluh"/>
<Button Content="Test" />
</StackPanel>
</Grid>
【问题讨论】:
-
Sal 习惯上对有帮助的答案进行投票,并将对您的问题的答案标记为已接受。
标签: c# wpf templates styles resourcedictionary