6

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

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

4

2 回答 2

9

可能Content是 null 而不是String.Empty

您可以尝试使用TargetNullValue

<DataTrigger Binding="{Binding Content, ElementName=lblCarrier,TargetNullValue=''}" Value="">
      <Setter Property="Visibility" Value="Hidden" />
</DataTrigger>
于 2013-03-28T14:08:44.517 回答
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}}"/>
于 2013-03-28T14:07:45.597 回答