WPF Class and corresponding Visual Style Inheritance

前端 未结 1 920
借酒劲吻你
借酒劲吻你 2021-01-26 06:11

I\'ve looked but apparently can\'t get the syntax correct when correlating to classes and styles. I have controls that have certain behavior. Some I derive to add additional b

相关标签:
1条回答
  • 2021-01-26 06:37

    Ok, I've stumbled into what APPEARS to be working as the answer, but don't understand why... If I try to change the style for the MyLabel2 (which is the second derived instance) from

    <Style x:Key="styleMyLabel2" TargetType="{x:Type local:MyLabel2}" BasedOn="{StaticResource styleMyLabel}" >
       <Setter Property="FontSize" Value="22" />
    </Style>
    

    to (just removing the x:Key element)

    <Style TargetType="{x:Type local:MyLabel2}" BasedOn="{StaticResource styleMyLabel}" >
       <Setter Property="FontSize" Value="22" />
    </Style>
    

    the XAML works... WITHOUT having to explicitly associate the "Style" to be used. It finds it based on the class association directly.

    <src:MyLabel2 Content="Now Works as expected"/>
    

    Now that it works, can someone maybe explain why the extra use of the x:Key reference kills it? ie: if you have the x:key, its not implied by the class instance, but not having it, the direct class DOES find it automatically.

    EXPANDED FROM MY PLAYING AROUND WITH STYLES...

    So, here is some extras that I've found out. A style can be defined more than once to the same TARGET TYPE... However, one can have an x:key reference, and another a BasedOn reference. This APPEARS to be like overloading a function with same number, but different data type parameters.

    In my problem, as soon as the "x:Key" reference was added to the style, any direct class instances of the "TargetType" were NOT automatically linked up to the proper style, almost like the style declaration with the "x:key" REQUIRES any instances of a class to explicitly add the style context within the xaml of the control. So now, how to have it BOTH ways. I created a SECOND style with the TargetType as the baseclass, but had ITs BasedOn pointing to the x:key referenced one. This way, I get the default customization of the style, yet can STILL assign it to the baseclass and the derived class as well, so all 3 versions of a control can be automatically synchronized with the corresponding Style without EXPLICIT referencing.

    <Style TargetType="Label" x:Key="wpfBaseLabel">
       <Setter Property="FontSize" Value="11" />
    </Style>
    
    <Style TargetType="Label" BasedOn="{StaticResource wpfBaseLabel}" />
    
    <Style TargetType="{x:Type local:MyLabel}" BasedOn="{StaticResource wpfBaseLabel}">
       <Setter Property="Foreground" Value="Blue" />
    </Style>
    

    So, now, within the final XAML, I can have all 3 "classes" used with or without explicit style association.

    0 讨论(0)
提交回复
热议问题