Question

I'm 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 don't 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.

I want to Style the text as well. Can I do this using a TextBox, or do I need to go to a RichTextBox? My underlying value is just a straight string.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top