WPF Show / Hide Trigger Control

I am new to WPF and I am trying to create xaml logic to show / hide a control based on the AllowMiscTitle value in the ViewModel. Xaml consists of two fields: combobox standard fragments ("Mr", "Mrs", ..., "Other") when "Other" is selected. I want the text box to display.

I created the following xaml:

<DockPanel Validation.Error="Validation_Error" HorizontalAlignment="Stretch"> <ComboBox ItemsSource="{Binding Path=Titles, Mode=OneTime}" Text="{Binding Path=Title}"/> <TextBox x:Name="TxtBxTitle" Margin="5,5" Visibility="Visible"> <TextBox.Style> <Style> <Style.Triggers> <DataTrigger Binding="{Binding Path=AllowMiscTitle}" Value="false"> <Setter Property="TextBox.Visibility" Value="Hidden"/> </DataTrigger> </Style.Triggers> </Style> </TextBox.Style> </TextBox> </DockPanel> 
+4
source share
3 answers

That Trigger will not work because you explicitly set the Visibility property in the TextBox

Do it like this:

 <TextBox x:Name="TxtBxTitle" Margin="5,5"> <TextBox.Style> <Style> <Style.Triggers> <DataTrigger Binding="{Binding Path=AllowMiscTitle}" Value="false"> <Setter Property="TextBox.Visibility" Value="Hidden"/> </DataTrigger> </Style.Triggers> </Style> </TextBox.Style> </TextBox> 

The reason for this is the priority of the property of the dependency property .

+5
source

Exist

 <BooleanToVisibilityConverter x:Key="BoolToVis"></BooleanToVisibilityConverter> 

You can use it as following

 <TextBox Visibility="{Binding YourPropertyName, Converter={StaticResource BoolToVis}}"></TextBox> 
+3
source

If I asked the question correctly: -

If your selected value is bound to some property in ViewModel, for example: -

 private string _GenderType; public string GenderType { get { return _GenderType; } set { _GenderType= value; RaisePropertyChanged("GenderType"); 

In xaml: -

 <TextBox.Style> <Style> <Setter Property="TextBox.Visibility" value="Hidden"/> <Style TargetType="{x:Type TextBox}"> <Style.Triggers> <DataTrigger Binding="{Binding Path=GenderType,ElementName=Combo1}" Value="Other"> <Setter Property="Visibility" Value="Visible"/> </DataTrigger> </Style.Triggers> </Style> </TextBox.Style> 
0
source

Source: https://habr.com/ru/post/1492033/


All Articles