WPF觸發(fā)器變化相應(yīng)控件外觀
WPF開發(fā)工具的主要用途就是實(shí)現(xiàn)圖形界面的顯示功能。在學(xué)習(xí)的過程中我們有許多需要深入研究的內(nèi)容。比如,除了定義控件的默認(rèn)外觀外,也許我們想還定義當(dāng)外界刺激我們的控件時,控件外觀做出相應(yīng)的變化,這是我們需要觸發(fā)器。參考以下代碼: #t#
- < Button Content="test btn"
Grid.Column="1" Grid.ColumnSpan="1"
Grid.Row="1" Grid.RowSpan="1" > - < Button.Template>
- < ControlTemplate>
- < !--定義視覺樹-->
- < Grid>
- < Ellipse Name="faceEllipse" Width="
{TemplateBinding Button.Width}" Height="
{TemplateBinding Control.Height}"
Fill="{TemplateBinding Button.Background}"/> - < TextBlock Name="txtBlock" Margin="
{TemplateBinding Button.Padding}"
VerticalAlignment="Center" Horizontal
Alignment="Center" Text="{Template
Binding Button.Content}" /> - < /Grid>
- < !--定義視覺樹_end-->
- < !--定義觸發(fā)器-->
- < ControlTemplate.Triggers>
- < Trigger Property="Button.
IsMouseOver" Value="True"> - < Setter Property="Button.
Foreground" Value="Red" /> - < /Trigger>
- < /ControlTemplate.Triggers>
- < !--定義觸發(fā)器_End-->
- < /ControlTemplate>
- < /Button.Template>
- < /Button>
在上面的WPF觸發(fā)器代碼中注意到< ControlTemplate.Triggers>... < /ControlTemplate.Triggers>之間的部分,我們定義了觸發(fā)器 < Trigger Property="Button.IsMouseOver" Value="True">,其表示當(dāng)我們Button的IsMouseIOver屬性變成True時,將使用設(shè)置器< Setter Property="Button.Foreground" Value="Red" /> 來將Button的Foreground屬性設(shè)置為Red。這里有一個隱含的意思是:當(dāng)Button的IsMouseIOver屬性變成False時,設(shè)置器中設(shè)置的屬性將回復(fù)原值。
你可以粘貼以下代碼到XamlPad查看效果:
- < Window xmlns="http://schemas.
microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com
/winfx/2006/xaml" Title="ControlTemplateTest"
Height="300" Width="300" >- < Grid ShowGridLines="True">
- < Grid.ColumnDefinitions>
- < ColumnDefinition Width="0.2*"/>
- < ColumnDefinition Width="0.6*"/>
- < ColumnDefinition Width="0.2*"/>
- < /Grid.ColumnDefinitions>
- < Grid.RowDefinitions>
- < RowDefinition Height="0.3*"/>
- < RowDefinition Height="0.3*"/>
- < RowDefinition Height="0.4*"/>
- < /Grid.RowDefinitions>
- < Button Content="test btn"
Grid.Column="1" Grid.ColumnSpan="1"
Grid.Row="1" Grid.RowSpan="1" >- < Button.Template>
- < ControlTemplate>
- < !--定義視覺樹-->
- < Grid> < Ellipse Name="faceEllipse" Width="
{TemplateBinding Button.Width}" Height="
{TemplateBinding Control.Height}"
Fill="{TemplateBinding Button.Background}"/>- < TextBlock Name="txtBlock" Margin=
"{TemplateBinding Button.Padding}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Text="{TemplateBinding Button.Content}" />- < /Grid>
- < !--定義視覺樹_end-->
- < !--定義觸發(fā)器--> < ControlTemplate.Triggers>
- < Trigger Property="Button.IsMouseOver"
Value="True">- < Setter Property="Button.Foreground"
Value="Red" />- < /Trigger> < /ControlTemplate.Triggers>
- < !--定義觸發(fā)器_End--> < /ControlTemplate>
- < /Button.Template>
- < /Button>
- < /Grid>
- < /Window>
以上就是對WPF觸發(fā)器的相關(guān)應(yīng)用方法介紹。