wpf引用外部样式及外部样式的复杂写法--------WPF
首先建一个 资源词典文件,名字叫sssss.xaml,我在里面写了几个样式。。。样式里也用到了触发器。每个资源标签都有一个key。。引用的时候需要
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Style x:Key="nihai" TargetType="{x:Type Label}">
<Setter Property="Height" Value="30"></Setter>
<Setter Property="Width" Value="100"></Setter>
<!--普通的setter标签只是给予这个控件属性赋值
但是要在外部样式中给控件添加事件,就必须重绘,就要用到下面这个属性Template-->
<Setter Property="Template">
<Setter.Value>
<!--这个标签就是模板的意思,表示当前控件的模板。它的优先级最大,,如果这个标签下没有内容
那么上面setter再怎么赋值,控件都显示为空-->
<ControlTemplate TargetType="{x:Type Label}" >
<!--既然重绘,就必须要内容-->
<Grid>
<Label Background="Green">nihao</Label>
</Grid>
<!--给当前重绘的控件模板加一个动画事件,,,,据测试,在上面的label中加事件不管用-->
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="xunhuan" Storyboard.TargetProperty ="Height" To="100" Duration="0:0:0:2">
</DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
然后在窗体里面xaml中引用
<Window x:Class="WPF_Tetst.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPF_Tetst"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<!--这是引用资源文件-->
<Window.Resources>
<ResourceDictionary >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="sssss.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid RenderTransformOrigin="0.484,0.525">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="255*"/>
<ColumnDefinition Width="262*"/>
</Grid.ColumnDefinitions>
***<Label Style="{DynamicResource nihai}" >***
<!--Style标签里面的内容,则是引用资源文件里面的具体样式-->
<CheckBox Name="chenx" Style="{StaticResource CheckStyle1}"/>
<!--Style标签里面的内容,则是引用资源文件里面的具体样式-->
<Button x:Name="button" Content="你好"
HorizontalAlignment="Left" VerticalAlignment="Top"
Width="75" Margin="10,11,0,0" Height="19"
Grid.Column="1" Style="{StaticResource buttonMouseOver}" />
</Grid>
</Window>
但是,一般资源文件都是共享的,全局都会用,通常会跨项目引用。。这时候是这样引用的
<UserControl.Resources>
<ResourceDictionary >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/程序集A ;component/....." />
<ResourceDictionary Source="/MEFA.Controls;component/Treeview/ScrollView_Self.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
在引用图片等资源文件的时候也可以这样
<Button x:Name="PART_InputButton" HorizontalAlignment="Right" Width="30" Content="nihao">
<Button.Background >
<ImageBrush ImageSource="/MEFA.Controls;component/Resources/Images/downarrow.jpg" Stretch="Fill"/>
</Button.Background>
</Button>