简体   繁体   中英

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?

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, eg:

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

You can use a DataTrigger to set the text, visibility, and appearance of the textbox based on the value in the ViewModel. This seems like the simplest solution.

<TextBox>
   <TextBox.Style>
       <Style TargetType="TextBox">
           <Style.Triggers>
                <DataTrigger Binding="{Binding Path=TheBoolean}" Value="True">
                     <Setter Property="Visibility" Value="Visible" />
                     <Setter Property="Background" Value="Red" />
                     ...
                </DataTrigger>
           </Style.Triggers>
       </Style>
   </TextBox.Style>
</TextBox>

Another option is to create an IValueConverter to convert the bool to get the text, visibility, and color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM