`

How to inherit XAML style and override property of child element?

阅读更多

The question


how to inherit XAML style and override some the property of the child element/

the problem

there is a very good question indeed, times are you need to define a base button that you want the derived classs to override. 

 

This article is about the principle tha how you can override the style inherited from the base style.

 

 


the solution

It is more a best practise/guide rather than the solutoin, there is a good artile on on this discussion on the stackoverlow already, so that yoy might have a look here

 


the note "The standard approach to making a customizable control template is to use TemplateBinding in the template to bind to properties  of the control, and then to set those properties in the child styles."

 

 

and here ist one of the example that you can find the stackoverflow forum.

 

 

<StackPanel>
    <StackPanel.Resources>
        <Style x:Key="BaseButtonStyle" TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}">
                            <ContentPresenter/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="BlueButtonStyle" TargetType="Button"
               BasedOn="{StaticResource BaseButtonStyle}">
            <Setter Property="Background" Value="Blue"/>
        </Style>
        <Style x:Key="RedButtonStyle" TargetType="Button"
               BasedOn="{StaticResource BaseButtonStyle}">
            <Setter Property="Background" Value="Red"/>
        </Style>
    </StackPanel.Resources>
    <Button Style="{StaticResource RedButtonStyle}">Red</Button>
    <Button Style="{StaticResource BlueButtonStyle}">Blue</Button>
</StackPanel>

 

 

 

 

The note: 

Below is a more elaborated example of how you can overrid the style to make the togglebutton to have different image depending on the IsChecked status.

 

 

<Style x:Key="_icoToggleButton"
           BasedOn="{x:Null}"
           TargetType="{x:Type ToggleButton}">
    <Style.Resources>
      <BitmapImage x:Key="_imageOnSource"
                   UriSource="pack://application:,,,/Resources/Images/excel_icon.gif" />
      <BitmapImage x:Key="_imageOffSource"
                         UriSource="pack://application:,,,/Resources/Images/refresh.PNG" />
    </Style.Resources>
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type ToggleButton}">
          <Grid>
            <Image Margin="2,2,2,2"
                           x:Name="image"
                    Source="{DynamicResource _imageOnSource}"
                         />
          </Grid>
          <ControlTemplate.Triggers>
            <Trigger Property="IsChecked" Value="True">
                    <Setter TargetName="image" Property="Source" Value="{DynamicResource _imageOnSource}" />
                    <Setter Property="ToolTip" Value="Click to Turn Off Auto Sorted/Filtered/Grouped by Fields" />
                  </Trigger>
                  <Trigger Property="IsChecked" Value="False" >
                    <Setter TargetName="image" Property="Source" Value="{DynamicResource _imageOffSource}" />
                    <Setter Property="ToolTip" Value="Click to Turn On Auto Sorted/Filtered/Grouped by Fields" />
                  </Trigger> 
                  <Trigger Property="IsChecked" Value="{x:Null}" >
                    <Setter TargetName="image" Property="Source" Value="{DynamicResource _imageOnSource}" />
                    <Setter Property="ToolTip" Value="Click to Turn On Auto Sorted/Filtered/Grouped by Fields" />
            </Trigger>
            <Trigger Property="IsFocused"
                         Value="True" />
            <Trigger Property="IsMouseOver"
                         Value="True">
              <Trigger.EnterActions>
                <BeginStoryboard Storyboard="{StaticResource _iconOverStoryboard}"
                                     x:Name="_iconOverStoryboard_BeginStoryboard" />
              </Trigger.EnterActions>
              <Trigger.ExitActions>
                <BeginStoryboard Storyboard="{StaticResource _iconAwayStoryboard}"
                                     x:Name="_iconAwayStoryboard_BeginStoryboard" />
              </Trigger.ExitActions>
            </Trigger>
            <Trigger Property="IsPressed"
                         Value="True">
              <Trigger.EnterActions>
                <BeginStoryboard Storyboard="{StaticResource _iconPressStoryboard}"
                                     x:Name="_iconPressStoryboard_BeginStoryboard" />
              </Trigger.EnterActions>
              <Trigger.ExitActions>
                <BeginStoryboard Storyboard="{StaticResource _iconReleaseStoryboard}"
                                     x:Name="_iconReleaseStoryboard_BeginStoryboard" />
              </Trigger.ExitActions>
            </Trigger>
            <Trigger Property="IsEnabled"
                         Value="False" />
          </ControlTemplate.Triggers>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>

 

 

 

Then you can define a child style as such.

 

 

 

<Style x:Key="_customizedIcoToggleButton"
           BasedOn="{StaticResource _customizedIcoToggleButton}"
           TargetType="{x:Type ToggleButton}">
    <Style.Resources>
      <BitmapImage x:Key="_imageOnSource"
                   UriSource="pack://application:,,,/Resources/Images/automatic.gif" />
      <BitmapImage x:Key="_imageOffSource"
                         UriSource="pack://application:,,,/Resources/Images/manua.PNG" />
    </Style.Resources>
    
</Style>

 

 

 

the new style "_customizedIcoToggleButton" now have a different images for on/off status.

 

分享到:
评论

相关推荐

    ComponentOne Studio for WinRT XAML2012 v3

    Based off our popular Silverlight controls and designed to enhance the rich user experience of the WinRT platform, these controls give you powerful and unique functionality to help you build better ...

    ComponentOne Studio for WinRT XAML 2013 v1

    ComponentOne Studio for... By default, each control supports a consistent Windows Store theme and can inherit the dark or light theme set by the user. Deliver uniform apps across devices with confidence.

    Professional Microsoft SQL Server 2008 Administration

    Once you know how to manage your SQL Server, you can learn in Chapter 5 how to automate many of the redundant monitoring and maintenance tasks. This chapter also discusses best practices on ...

    Odin2.0.15.rar

    or add a few lines of code to your existing class, and everything serializable shall be serialized. Yes, even polymorphic types! ? Powerful Lists: All arrays and lists implementing Microsoft's ...

    A Multi-Stage Modeling Framework for Web Service Composition

    net and defines it as an extended Petri net, in order to inherit the closure property of Petri nets. Some operators in the web service calculus are illustrated and mapped to the Petri nets operation. ...

    JavaScript Object Programming(Apress,2015)

    This brief book explains the advantages of the object model, inheritance, both classical and prototypical, and shows how these concepts can be implemented in JavaScript. It also shows how object ...

    AI技术论文

    how to morph a well-trained neural network to a new one so that its network function can be completely preserved. We define this as network morphism in this research. After morphing a parent network, ...

    C#语言规范 版本 4.0(English)

    Aspects of C#’s design that were directly influenced by versioning considerations include the separate virtual and override modifiers, the rules for method overload resolution, and support for ...

    JavaScript.Object.Programming.148421

    This brief book explains the advantages of the object model, inheritance, both classical and prototypical, and shows how these concepts can be implemented in JavaScript. It also shows how object ...

    Odin – Inspector and Serializer v3.0.9

    or add a few lines of code to your existing class, and everything serializable shall be serialized. Yes, even polymorphic types! Odin serialized prefabs are deprecated in 2018.3+ due to

    WPTools.v6.29.1.Pro

    - change in RTF reader to let section inherit the default layout, not the current page layout - fix of problem with table borders when also PageMirror was used. * change to DeleteMarkedChar. It now ...

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持D4-XE5

    + [enterprise] added property "ReportsFile" - path to file with reports to groups associations and cache delays + [enterprise] added property "ReportsListRenewTimeout" in server configuration + ...

    Sublime Text Build 3124 x64 Setup.exe

    API: Added functions to get and set visibility of the minimap, status bar, tabs and menu API: Modifications to a selection are now constrained to the valid range API: Updated Python 3.3 to commit 8e3...

    ASP.NET+Core+2+and+Angular+5-Packt+Publishing(2017).pdf

    we can say that PWAs inherit all the major concepts that were already part of the Reactive Manifesto and bring them further on with brand new features--such as Service Workers--that would not have ...

    stylecssvaribles.css

    - Houdini’s new API: `CSS.registerProperty({name:'--red', inherit:false, initialValue:'#e33'})` (of course not animatable) - style-attributes `&lt;div ie-style="--foo:bar"...` - cascade works - ...

    Object- Oriented Programming with Ansi-C

    and how we harness generality and program to catch mistakes earlier. Along the way we encounter all the jargon — classes, inheritance, instances, linkage, methods, objects, polymorphisms, and more —...

    inherit_js:简单继承模块

    继承js 简单继承模块 用法 function Parent() {} ... inherit(Parent, Child); Child.prototype.childMethod = function () { console.log('child method!'); }; var child = new Child(); child.chil

    New NHibernate + Sample Source Part2

    not only how to get objects into the database, but also how to get them out again * Custom SQL - specify the exact SQL that NHibernate should use to persist your objects. Stored procedures are ...

    New NHibernate + Sample Source Part1

    not only how to get objects into the database, but also how to get them out again * Custom SQL - specify the exact SQL that NHibernate should use to persist your objects. Stored procedures are ...

    NHibernate 2.0.1 + Movies + Sample Source Part2

    not only how to get objects into the database, but also how to get them out again * Custom SQL - specify the exact SQL that NHibernate should use to persist your objects. Stored procedures are ...

Global site tag (gtag.js) - Google Analytics