Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stackpanel visibility based on label content not working

Tags:

wpf

xaml

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>**

like image 513
user1884032 Avatar asked Mar 28 '13 14:03

user1884032


2 Answers

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>
like image 123
Richard Friend Avatar answered Nov 17 '22 05:11

Richard Friend


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}}"/>
like image 44
Hossein Narimani Rad Avatar answered Nov 17 '22 04:11

Hossein Narimani Rad