Styles and templates for the WPF QuickStart series (Style and template)

Source: Internet
Author: User

In the WPF desktop program, when we want to build a unified UI performance (the display is consistent across different operating systems), we need to use the styling and templating techniques in WPF. Simply put, if we need to simply give a button a width, height, margin, etc., you can use the style to specify this series of properties. The style can be understood as a collection of attributes. If you need to completely change the look of the control, you need to use the template technique, which is equivalent to giving the control a layer of skin, but the button is a button, and its original behavior (the Click event) still exists. And we just need to be able to define and rewrite styles and templates all over the XAML. Very simple and convenient.

First, learn the style with an example.

 <Window.Resources> <style x:key= "Numericstyle" targettype= "{x:type Button}" > <setter Pro Perty= "FontSize" value= "/> <setter property=" Margin "value=" 4 "/> <setter property="                    Padding "value=" 6 "/> <setter property=" Effect "> <Setter.Value> <dropshadoweffect color= "Blue"/> </Setter.Value> </Setter> </style            > <style targettype= "button" x:key= "Operatorstyle" basedon= "{StaticResource Numericstyle}" >                <setter property= "FontWeight" value= "Extrabold"/> <setter property= "Effect" >            <Setter.Value> <dropshadoweffect color= "Red"/> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid> &LT;GRID.ROWDEFINITIONS&G            T <rowdefInition height= "Auto"/> <rowdefinition height= "Auto"/> <rowdefinition height= "Auto"/> <rowdefinition height= "Auto"/> <rowdefinition height= "Auto"/> </grid.rowdefinitio ns> <Grid.ColumnDefinitions> <columndefinition width= "Auto"/> <columndefini         tion width= "Auto"/> <columndefinition width= "Auto"/> <columndefinition width= "Auto"/> </Grid.ColumnDefinitions> <textbox background= "Cyan" isreadonly= "True" grid.columnspan= "4" Fontsiz E= "/> <button content=" 7 "style=" {StaticResource numericstyle} "grid.row=" 1 "/> <button conten t= "8" style= "{StaticResource numericstyle}" grid.row= "1" grid.column= "1"/> <button content= "9" style= "{Static Resource Numericstyle} "grid.row=" 1 "grid.column=" 2 "/> <button content=" 4 "style=" {StaticResource numericstyl   e} "grid.row=" 2 "/>     <button content= "5" style= "{StaticResource numericstyle}" grid.row= "2" grid.column= "1"/> <button Cont Ent= "6" style= "{StaticResource numericstyle}" grid.row= "2" grid.column= "2"/> <button content= "1" style= "{Stat Icresource Numericstyle} "grid.row=" 3 "/> <button content=" 2 "style=" {StaticResource numericstyle} "grid.row=" 3 "grid.column=" 1 "/> <button content=" 3 "style=" {StaticResource numericstyle} "grid.row=" 3 "grid.column=" 2 "/&        Gt <button content= "0" style= "{StaticResource numericstyle}" grid.row= "4"/> <button content= "=" style= "{Stati                Cresource Operatorstyle} "grid.row=" 4 "grid.column=" 1 "grid.columnspan=" 2 "> <Button.Effect> <dropshadoweffect color= "Green"/> </Button.Effect> </Button> <button Co Ntent= "+" style= "{StaticResource operatorstyle}" grid.row= "4" grid.column= "3"/> <button content= "-" style= "{S Taticresource Operatorstyle} "grid.row=" 3 "grid.column=" 3 "/> <button content=" X "style=" {StaticResource Operatorstyle} "Gr Id. row= "2" grid.column= "3"/> <button content= "/" style= "{StaticResource operatorstyle}" grid.row= "1" grid.column = "3"/> </Grid>

Operating effect:

As you can see from the example above,

1. The style contains a number of setters, each of which corresponds to a different set of properties. As the blog begins. A style is a set of properties;

2. You can set the TargetType in the style to indicate which control the style is used for;

3. Style can inherit, for example, the style of the action button inherits the style of the numeric button, uses Baseon, and then references the resource of the style;

4. Style priority, = button, set the Dropshadoweffect of the button in the style to red, and then inside the button we set Dropshadoweffect to blue, the final display of the effect can be seen, = The final color of the button is blue. Can be understood as a later person in the home.

The style can contain not only a series of setters, but also trigger. There are three types of Trigger,property trigger,event trigger,data Trigger in WPF. Below we introduce property Trigger, follow the above example, when the mouse click the button, set the transform effect.

        <style targettype= "button" x:key= "Operatorstyle"            basedon= "{StaticResource Numericstyle}" >            < Setter property= "FontWeight" value= "Extrabold"/>            <setter property= "Effect" >                <Setter.Value>                    <dropshadoweffect color= "Red"/>                </Setter.Value>            </Setter>            <style.triggers >                <trigger property= "ispressed" value= "True" >                    <setter property= "RenderTransform" >                        <Setter.Value>                            <translatetransform x= "4" y= "4"/>                        </Setter.Value>                    </setter >                </Trigger>            </Style.Triggers>        </Style>

The results are as follows:

Trigger represents a trigger when a certain condition is met. In the above example, when ispressed is true, the transform change is triggered, and when the ispressed is false, it is automatically restored to its original state, and no additional code is required to restore the initial state.

Not only can you use trigger in the style, but you can also use it in datatemplate,controltemplate.

Property trigger is for dependency properties, how do you trigger UI changes when normal properties change? So here's another trigger,data Trigger. Take a look at the example:

Xaml:

        <listbox horizontalalignment= "Center" itemssource= "{Binding.}"                        > <ListBox.ItemTemplate> <DataTemplate> <Grid>                            <border margin= "2" borderbrush= "Blue" borderthickness= "1" padding= "2" x:name= "_border" > <Grid> <Grid.RowDefinitions> &L T                                RowDefinition height= "Auto"/> <rowdefinition height= "Auto"/> </Grid.RowDefinitions> <textblock text= "{Binding Name}" fontsize= " "fontweight=" Bold "/> <textblock grid.row=" 1 "text=" {Binding authorname} "FontSize = "foreground=" "Blue"/> <textblock opacity= ". 5" fontweight= "Bold" fontstyle= "Itali C "foreground=" Red "textalignment=" right "grid.rowspan=" 2 "VerticalaliGnment= "Center" visibility= "Hidden" x:name= "_free" text= "free!"                    Margin= "4" fontsize= "/>" </Grid> </Border> </Grid><DataTemplate.Triggers> <datatrigger binding= "{Binding isfree}" Va Lue= "True" > <setter property= "Background" targetname= "_border" value= "Yellow"/> <setter property= "Visibility" value= "Visible" targetname= "_free"/> < ;/datatrigger> </DataTemplate.Triggers></DataTemplate> </ListBox.ItemTemplate> </ListBox>

C#:

    public partial class Mainwindow:window    {public        MainWindow ()        {            InitializeComponent ();            DataContext = new list<book>            {                new book {Name = "Windows internals",                authorname = "Mark Russinovich", I Sfree = False},                new book {Name = "AJAX Introduction",                authorname = "Bhanwar Gupta", Isfree = true},                new B ook {name = ' Essential COM ',                authorname = ' Don box ', Isfree = false},                new book {name = ' Blueprint for a succe Ssful Presentation ",                authorname =" Biswajit tripathy ", Isfree = true}            ;    }} public class book    {public        string Name {get; set;}        public bool Isfree {get; set;}        public string AuthorName {get; set;}    }

Operating effect:

DataTrigger finds a specific attribute based on the binding, which is triggered when the condition is met.

Below is a brief introduction to the event Trigger, see the sample code:

    <Grid>        <Grid.Triggers>            <eventtrigger routedevent= "Loaded" >                <beginstoryboard >                    <Storyboard>                        <doubleanimation from= "0" to= "1" duration= "0:0:5                            " storyboard.targetproperty= "Opacity"/>                    </Storyboard>                </BeginStoryboard>            </ eventtrigger>        </Grid.Triggers>        <textblock text= "Event Trigger Demo" fontsize= "    />" </Grid>

The effect of the operation, the grid transparency from 0 to 1.

Note: Event trigger can only be used for routed events.

Above we introduced three kinds of trigger, but they are all used with satisfying a certain condition and then triggering. If you want to meet some conditions before triggering, we can use MultiTrigger, see example:

    <Window.Resources> <style x:key= "Hoverbuttonstyle" targettype= "{x:type button}" > <sty Le.                        Triggers> <MultiTrigger> <MultiTrigger.Conditions> <condition property= "IsMouseOver" value= "True"/> <condition property= "IsDefault" value= " True "/> </MultiTrigger.Conditions> <setter property=" Background "value=                            "Cyan"/> <setter property= "Effect" > <Setter.Value>                <dropshadoweffect/> </Setter.Value> </Setter>    </MultiTrigger> </Style.Triggers> </Style> </Window.Resources> <stackpanel orientation= "Vertical" > <button content= "Move mouse Over Me" fontsize= "Horiz" Ontalalignment= "CenteR "margin=" padding= "6" x:name= "Thebutton" style= "{StaticResource hoverbuttonstyle}"/> <checkbo X content= "Default button" margin= "ischecked=" {Binding IsDefault, Elementname=thebutton, MODE=TW Oway} "fontsize="/> </StackPanel>

Operating effect:

Note: There are only two types of MultiTrigger, except for the above, and Multidatatrigger. Used to trigger when multiple data attributes meet a certain condition.

Here is an example of how ControlTemplate is used,

For example, there are two "pristine" radiobutton,

    <stackpanel orientation= "Horizontal" >        <radiobutton content= "Job Practice" ischecked= "True" margin= "10,5,10,0" />        <radiobutton content= "Exam quiz" margin= "0,5,10,0"/>    </StackPanel>

The results shown in win 10 and win 7 are as follows:

The same controls appear inconsistent under WIN10 and Win7, we have a "facelift" for RadioButton,

    <Window.Resources> <style x:key= "RadioButtonStyle01" targettype= "RadioButton" > <sette R property= "Snapstodevicepixels" value= "true"/> <setter property= "Overridesdefaultstyle" Value= "true"/&            Gt            <setter property= "Foreground" value= "#565656"/> <setter property= "Background" value= "#EDEEEF"/>            <setter property= "FontSize" value= "a"/> <setter property= "fontweight" value= "Bold"/> <setter property= "Width" value= "/> <setter property=" Height "value=" "/> < Setter property= "Template" > <Setter.Value> <controltemplate targettype= "Radi Obutton "> <border x:name=" Mainborder "borderthickness=" 1 "borderbrush=" #8B99BC "cornerradius= "1" background= "#F0F2F2" > <Grid> <image x:name= "IMGC Hecked "VIsibility= "collapsed" source= "/controltemplatingdemo;component/resources/images/completed_02.png" Width= "20" height= "horizontalalignment=" "Right" verticalalignment= "Top" margin= "0,-8,-10,0"/> &L T                                                       ContentPresenter recognizesaccesskey= "True" content= "{TemplateBinding contentcontrol.content}"                                                       Contenttemplate= "{TemplateBinding contentcontrol.contenttemplate}" contentstringformat= "{TemplateBinding Contentcontrol.contentstringformat}" margin= "5" Horizontal Alignment= "Center" verticalalignment= "center" snapstodevicepixels= "{ TemplateBinding uielement.snapstodevicepixels} "/> </Grid> < /border> <ControlTemplate.Triggers> <trigger property= "Ische             Cked "value=" True ">                   <setter targetname= "Mainborder" property= "Background" value= "#239FFF"/> <setter targetname= "imgchecked" property= "Visibility" value= "Visible"/> <set ter property= "Foreground" value= "white"/> <setter targetname= "Mainborder" property= "B Orderbrush "value=" #239FFF "/> </Trigger> </controltemplate.t        riggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <stackpanel orientation= "Horizontal" > <radiobutton Con tent= "Job Practice" style= "{StaticResource RadioButtonStyle01}" ischecked= "True" margin= "10,5,10,0"/> <radiobutton Co ntent= "test test" style= "{StaticResource RadioButtonStyle01}" margin= "0,5,10,0"/> </StackPanel>

RadioButton after ControlTemplate-style rewrite:

RadioButton now looks the same under different operating systems.

In order to get the same display effect under different OS, we need to override the WPF control style. The override of a control's style can be understood as a reorganization of its performance. We can view the internal construction of the control through blend, and then override the control based on the requirements of the project.

Thank you for reading. Code click here to download.

Styles and templates for the WPF QuickStart series (Style and template)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.