Im using a TextBox control and want the characters to turn red after a certain number of characters to show users they have typed too much. I dont want to truncate as the user might have typed that "really important thought" and if i truncated they would lose it. I have validation on my underlying business model which tells me when the input is invalid and i style my textbox to show invalidity. but i want to style the text as well. can i do this using a textbox, or do i need to go to a rich text box. my underlying value is just a straight string.
views:
637answers:
2I assume you're using the stock WPF validation mechanism - ValidationRules
. If so, you should define a Trigger
on Validation.HasError == true
, and set TextBox
properties as needed. For example, the following will highlight text with red if it's invalid.
<TextBox>
<TextBox.Text>
<Binding ...>
<Binding.ValidationRules>
...
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
This is a kind of crazy answer and I haven't tried it yet, but if it works, you would be able to continue to use a textbox instead of a rich textbox.
What if you use a gradient brush to paint the text (or if not the text, the textbox background, if that was acceptable to you).
You would build the gradient so that it was white up to the point the input got too long and red after-wards. Of course until the text got too long the brush would be all white.
This would involve text measurement to get the gradient definition right (since proportional fonts would cause the valid area to be a different size depending on the letters entered) and would require the brush be calculated and assigned at each character entered.