Giffesnaffen
Giffesnaffen

Reputation: 560

Datatrigger on empty string

How can a DataTrigger change the visibility of stackpanel, based on a binded string? I have the following Xaml

<StackPanel HorizontalAlignment="Right" 
            Orientation="Horizontal" 
            Grid.Column="1"
            Background="#FF7a7a7a">
    <StackPanel.Style>
        <Style TargetType="{x:Type StackPanel}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding SearchText}" Value="">
                    <Setter Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
    Content....
   </StackPanel>

I Know that SearchText gets updates and binds properly outside the StackPanel

Could somebody point me in the right direction?

Upvotes: 26

Views: 31565

Answers (4)

Buzzy
Buzzy

Reputation: 1924

Correct using String.Empty in XAML:

xmlns:sys="clr-namespace:System;assembly=mscorlib"
...
<DataTrigger Binding="{Binding SearchText}" Value="{x:Static sys:String.Empty}">

Upvotes: 16

Rahul Misra
Rahul Misra

Reputation: 669

Try this

<StackPanel.Style>
                                        <Style TargetType="StackPanel">
                                            <Setter Property="Visibility" Value="Collapsed"/>
                                            <Style.Triggers>
                                                <DataTrigger Binding="{Binding YourBoundPropertyName}" Value="True">
                                                    <Setter Property="Visibility" Value="Visible"/>

                                                </DataTrigger>
                                            </Style.Triggers>
                                        </Style>
                                    </StackPanel.Style>

Upvotes: 0

trinaldi
trinaldi

Reputation: 2950

Weird as it might sound, the code below works for me:

<StackPanel Background="#FF7a7a7a">
    <StackPanel.Style>
        <Style TargetType="{x:Type StackPanel}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Text, ElementName=textBlock}" Value="">
                    <Setter Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
    <TextBox x:Name="textBlock" Text="" Width="100" Height="30"></TextBox>
</StackPanel> 

Can you tell the value your Property is sending?

Upvotes: 0

Fede
Fede

Reputation: 44038

This:

<DataTrigger Binding="{Binding SearchText}" Value="">
   <Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>

will work for empty string (""), however it will not work for null.

Add another DataTrigger for the null case:

<DataTrigger Binding="{Binding SearchText}" Value="{x:Null}">
   <Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>

Upvotes: 45

Related Questions