views:

637

answers:

2

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.

A: 

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>
Pavel Minaev
this will change the colour of the text in the text box, what i want is to only change the text colour after a certain character. I want the first characters to be black and if they type over 200 for example the 201st turns red.
Aran Mulholland
Okay, I understand now. Yes, you will definitely need `RichTextBox` for that sort of thing, and most likely a custom converter to boot.
Pavel Minaev
A: 

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.

automatic
sounds interesting, you're thinking outside the square. but also a lot of work, i think i will investigate the rich text box, and binding a string to it.
Aran Mulholland