Setting Foreground Color of Entire Window

后端 未结 4 904
小蘑菇
小蘑菇 2020-12-08 10:42

I\'d like to set the foreground (text) color to all of my elements You\'d think this would be easy, but it\'s not...


   <         


        
4条回答
  •  忘掉有多难
    2020-12-08 11:06

    This is because such controls as Label and CheckBox override the Foreground property in their styles.

    Below is an example a typical logical tree of elements that shows how the value specified on the Window level travels down the tree:

    Window (Red [Local]) 
      -> Grid (Red [Inherited]) 
         -> ListBox (Red [Inherited]) 
            -> ListBoxItem (Red [Inherited]) 
               -> StackPanel (Red [Inherited]) 
                  -> Label (Black [Style])
                     -> TextBlock (Black [Inherited])
                  -> TextBlock (Red [Inherited])
    

    In square brackets the source of the value is shown.

    As you can see the inheritance breaks on the Label itself because it has the Foreground property set in its default style:

    
    

    As a workaround for this we can use the following trick. Define the default style for such controls (as Label) in the application (in App.xaml or in the Window inself). And in that default style override the Foreground property to set a relative source binding to the nearest ancestor of the control that still has the desired value:

    
    
    
    

    After that our tree will look like this:

    Window (Red [Local]) 
      -> Grid (Red [Inherited]) 
         -> ListBox (Red [Inherited]) 
            -> ListBoxItem (Red [Inherited]) 
               -> StackPanel (Red [Inherited]) 
                  -> Label (Red [Binding to StackPanel.(TextElement.Foreground)])
                     -> TextBlock (Red [Inherited])
                  -> TextBlock (Red [Inherited])
    

    As you can see, our binding restores the inheritance.

    Such styles need to be defined for each element that overrides the Foreground property in its style. As @Duane suggested, to not duplicate the binding in each style the BasedOn capability can be used:

    
    
    
    
    
    

    Hope this helps.

提交回复
热议问题