Generic 代码 :
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ResourceLib"> <ResourceDictionary.MergedDictionaries > <ResourceDictionary Source="/ResourceLib;component/Styles1.xaml"></ResourceDictionary> </ResourceDictionary.MergedDictionaries> <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}"> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary>
Styles1.xaml代码:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ResourceLib"> <Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:Styles1},ResourceId=bigFontStyle}" > <Setter Property="Control.FontFamily" Value="Times New Roman"></Setter> <Setter Property="Control.FontSize" Value="18"></Setter> <Setter Property="Control.FontWeight" Value="Bold"></Setter> </Style> </ResourceDictionary>
Styles1.cs代码
public partial class Styles1 { public static ComponentResourceKey BigFontStyleKey { get { return new ComponentResourceKey(typeof(Styles1), "bigFontStyle"); } } }
ResourceStyle.xaml 代码:
<Window x:Class="WPFLearning.StyleTemplates.ResourceStyle" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:rl="clr-namespace:ResourceLib;assembly=ResourceLib" Title="ResourceStyle" Height="300" Width="300"> <Grid> <Button Style="{DynamicResource {x:Static rl:Styles1.BigFontStyleKey}}">Hi, i use a component sytle</Button> </Grid> </Window>
ResourceLib.csproj 实现隐藏代码
<Compile Include="Styles1.cs"> <DependentUpon>Styles1.xaml</DependentUpon> </Compile>
显示效果
项目结构: