`

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.

    Java - A Beginner’s Guide - Sixth Edition - Herbert Schildt

    This chapter explains how to define subclasses that inherit from superclasses and how to override methods. It also covers access modifiers and visibility rules, which determine how members of a class...

    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 ...

    Objective-C for Absolute Beginners: iPhone and Mac Programming Made Easy

    Inheritance enables one class to inherit properties and behaviors from another. Polymorphism allows objects of different classes to be treated as if they were the same type. **Apple's Developer ...

    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, ...

    CSharp 3.0 With the .NET Framework 3.5 Unleashed(english)

    - **Inheritance**: Inheritance allows you to create new classes that inherit properties and methods from existing classes. - **Encapsulating Object Internals**: Encapsulation is the practice of hiding...

    C# - CSharp 12 in a Nutshell The Definitive Reference

    Understanding how to declare and use variables and parameters effectively is crucial for writing efficient and maintainable code. **Expressions and Operators** Expressions are combinations of values...

    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 + ...

    salesforce dev 501 Notes

    They inherit from the `ActionSupport` class and can override or add new methods to the base controller. Understanding the differences between these two is important for effective development. Custom...

    INTRODUCTION TO PYTHON SCRIPTING FOR MAYA ARTISTS.

    - **Inheritance and Polymorphism:** Inheritance allows classes to inherit properties and methods from parent classes. Polymorphism allows objects to take on multiple forms. **Documenting Your Code** ...

    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 - ...

    计算机英语第二版清华第5单元.pdf

    For instance, 'It is possible to be familiar with various aspects of computer software without being concerned with details of how the computer hardware operates' showcases the use of the dummy ...

    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 —...

Global site tag (gtag.js) - Google Analytics