In a button's control template, how can I set the color of contained text?

后端 未结 3 1141
半阙折子戏
半阙折子戏 2021-02-20 10:37

Using Silverlight 4 & WPF 4, I\'m trying to create a button style that alters the text color of any contained text when the button is mouseover\'d. Since I\'m trying to make

3条回答
  •  自闭症患者
    2021-02-20 10:59

    This is a tricky one. The foreground is a property of the button that is passed through to the controls the content presenter creates. Because it is a dependency property and not a property of the controls available in the template it is hard to animate it using pure xaml.

    MSDN Has a couple samples on how to change foreground color. However, it doesn't sound like you want to do this work from code. (http://msdn.microsoft.com/en-us/library/system.windows.controls.button(VS.95).aspx)

    The button's default template is holding you back. As you've noticed, button is a content-less control; meaning the designer can push some random visual object inside of it. Being content-less forces the foreground property to be a member of the template rather than the control because there isn't a guarranteed component to set the color to. Which is why there is a content presenter inside of it.

    So now you have two options. 1. Easy but not flexible (pure xaml), 2. Create your own control that does everything a button does (requires code and lots of testing)

    I'll implement #1 for you.

    If you modify the template of the button and remove the content presenter you can place inside of it two textblocks. One with the normal color, the other with your mouse over color.

           
     
    

    Notice how the Text properties of the Textblocks are bound to the content from button. This becomes a problem if there is ever a need to bind to ANYTHING other than text. TextBlocks simply can't show anything but AlphaNumeric values.

    Also notice that by default I have collapsed the visibility on the RedBlock.

    Then, in my MouseOver VisualState's Storyboard I can animate the RedBlock to be visible and the BlueBlock to be invisible:

    
        
            
                Visible
            
        
    
    
        
            
                Collapsed
            
        
    
    

    It feels like a hack, and I probably wouldn't implement this button in lots of places. I'd want to make my own Button with good DependencyProperties to bind to. One each for HighlightForeground and Text. I'd also want to hide or atleast throw an exception if someone tried to set the content to anything other than AlphaNumeric values. However, the XAML would be the same, I'd have different textblocks for different visual states.

    I hope this helps.

    Have a great day.

    -Jeremiah

提交回复
热议问题