Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Showing / Hiding a control with triggers

Tags:

mvvm

wpf

triggers

I'm new to WPF and I trying to create xaml logic to show / hide a control based on the value of the AllowMiscTitle on the ViewModel. The xaml consist of two fields a combobox of the standard tiles ("Mr", "Mrs", ..., "Other") when "Other" is selected I want the textbox to display.

I've created the follow 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>
like image 498
user1683456 Avatar asked Jul 18 '13 08:07

user1683456


2 Answers

That Trigger won't work because you have set Visibility property explicitly in 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 Dependency property value precedence.

like image 189
Kapitán Mlíko Avatar answered Nov 03 '22 18:11

Kapitán Mlíko


There is a

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

You can use it as following

<TextBox Visibility="{Binding YourPropertyName, Converter={StaticResource BoolToVis}}"></TextBox>
like image 6
Nitesh Avatar answered Nov 03 '22 16:11

Nitesh