我有一个由列表视图组成的 UserControl,它看起来像:
<UserControl
....
<UserControl.Resources>
<Style TargetType="Thumb">
<!-- Style Content -->
</Style>
<Style TargetType="GridViewColumnHeader">
<!-- Style Content -->
</Style>
<Style TargetType="{x:Type ScrollBar}">
<!-- Style Content -->
</Style>
<Style TargetType="{x:Type ScrollViewer}">
<!-- Style Content -->
</Style>
<Style TargetType="{x:Type ListViewItem}">
<!-- Style Content -->
</Style>
</UserControl.Resources>
<ListView Name="ListView1" >
<!-- ListViewContent -->
</Style>
</UserControl>
我有 3 个用户控件,它们之间唯一不同的是<UserControl.Resources>
. 不必仅仅因为我需要不同的外观和感觉就必须创建具有相同功能的多个控件。我现在要做的是将所有样式<UserControl.Resources>
合并为一种样式。如果我设法将所有这些样式归为一个,我将能够删除 3 个控件并将样式更改为:
<ListView Style={DynamicResource style1} ...
目前,如果我这样做
<UserControl.Resources>
<Style x:Key="style1">
<!-- Place all styles in here -->
</Style>
</UserControl.Resources>
这没用。
编辑
感谢 iltzortz 的回答,我现在有了:
字典1.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="Grid">
<Setter Property="Background" Value="Green"></Setter>
</Style>
<SolidColorBrush x:Key="Foo" Color="Red"></SolidColorBrush>
</ResourceDictionary>
字典2.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="Grid">
<Setter Property="Background" Value="Black"></Setter>
</Style>
<SolidColorBrush x:Key="Foo" Color="Orange"></SolidColorBrush>
</ResourceDictionary>
我的用户控件:
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="97" d:DesignWidth="91">
<UserControl.Resources>
<ResourceDictionary Source="Dictionary1.xaml" ></ResourceDictionary>
</UserControl.Resources>
<Grid >
<Ellipse Fill="{DynamicResource Foo}" />
</Grid>
</UserControl>
我像这样动态更改资源字典:switching wpf resource dictionaries at runtime