user1884032
user1884032

Reputation: 347

stackpanel visibility based on label content not working

I have a stack panel that I want to make visible based on a label's content. Just not sure why it isnt working for me. What's highlighted in bold is what I want to hide. Any suggestion?

<StackPanel Orientation="Horizontal">
<Label Nane="lblCarrier" Content="{Binding Path=Carrier}" />
**<StackPanel Orientation="Horizontal">
    <StackPanel.Style>
        <Style TargetType="StackPanel">
            <Setter Property="Visibility" Value="Visible" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Content, ElementName=lblCarrier}" Value="">
                    <Setter Property="Visibility" Value="Hidden" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
    <Label x:Name="lblCarrierGrade" Content="Grade Carrier:" />
    <TextBox x:Name="txtCarrierGrade1" />
    <TextBox x:Name="txtCarrierGrade2" />
</StackPanel>**

Upvotes: 6

Views: 4435

Answers (2)

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

Why not using a converter? Add a class file to you project like this:

class VisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return string.IsNullOrEmpty(value as string) ? Visibility.Hidden : Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

In your Window definition add this:

xmlns:myNamespace="clr-namespace:[YourProjectName]"

Then somewhere in the resources add this

<myNamespace:VisibilityConverter x:Key="myConverter"/>

Now you can use it:

 <Style TargetType="StackPanel">
        <Setter Property="Visibility" 
                Value="{Binding Content, ElementName=lblCarrier,
                                Converter = {StaticResources myConverter}}"/>

Upvotes: 1

Richard Friend
Richard Friend

Reputation: 16018

It could be that the Content is null rather than String.Empty.

You could try using TargetNullValue

<DataTrigger Binding="{Binding Content, ElementName=lblCarrier,TargetNullValue=''}" Value="">
      <Setter Property="Visibility" Value="Hidden" />
</DataTrigger>

Upvotes: 9

Related Questions