Search code examples
wpftextboxadorner

Best way to have a TextBox show a message based on a bool in the ModelView


I have a TextBox that needs to have its border change color and then display a message below the text box. This message should be displayed/hidden based on a bool value in the model. What is the best way to achieve this?


Solution

  • There are a ton of different ways of doing this. If you're only going to do this once, the simplest way is to add the TextBlock to the layout and use a style to hide it, e.g.:

    <StackPanel>
       <TextBox Text="{Binding Text, Mode=TwoWay}">
          <TextBox.Style>
             <Style TargetType="TextBox">
                <Setter Property="BorderBrush" Value="Lightgray"/>
                <Style.Triggers>
                   <DataTrigger Binding="{Binding IsValid}" Value="False">
                      <Setter Property="BorderBrush" Value="Red"/>
                   </DataTrigger>
                </Style.Triggers>
             </Style>
          </TextBox.Style>
       </TextBox>
       <TextBlock Text="This is the message displayed if IsValid is false.">
          <TextBlock.Style>
             <Style TargetType="TextBlock">
                <Setter Property="Visibility" Value="Collapsed"/>
                <Style.Triggers>
                   <DataTrigger Binding="{Binding IsValid}" Value="False">
                      <Setter Property="Visibility" Value="Visible"/>
                   </DataTrigger>
                </Style.Triggers>
             </Style>
           </TextBlock.Style>
       </TextBlock>
    </StackPanel>
    

    If this is something you want to be able to repeat, you'll want to make this into a template or a user control.

    Also, note that changing the visibility from collapsed to visible will change the overall layout, which could have all kinds of undesirable effects. Depending on your design, you might make the visibility default to hidden.