基于标签内容无效的stackpanel可见性

时间:2013-03-28 14:03:19

标签: wpf xaml

我有一个堆栈面板,我希望根据标签的内容使其可见。只是不确定为什么它不适合我。粗体突出显示的是我想要隐藏的内容。有什么建议吗?

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

2 个答案:

答案 0 :(得分:8)

可能是Content为空而不是String.Empty

您可以尝试使用TargetNullValue

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

答案 1 :(得分:1)

为什么不使用转换器?像这样添加一个类文件:

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();
    }
}

Window定义中添加以下内容:

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

然后在资源中的某处添加此

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

现在你可以使用它了:

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