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 boo开发者_如何转开发l 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, 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.
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.
精彩评论