如果标题为空,则隐藏整个Expander

时间:2014-12-25 14:26:35

标签: wpf triggers datatrigger wpf-style

我有一个Expander WPF控件,标题的模板是一个简单的TextBlock。如果TextBlock.Text(从外部动态填充)为null或为空,我想隐藏整个扩展器。

<Expander>
    <Expander.Header>
        <TextBlock Text="{Binding Path=Name}"/>
    </Expander.Header>
</Expander>

2 个答案:

答案 0 :(得分:1)

您可以参考此示例。 Hide Expander ToggleButton if no child items in WPF

<强>的Xaml

  <ListBox x:Name="lstbx">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Expander x:Name="exp">
                <Expander.Header>
                    <TextBlock Text="{Binding Path=Name}"></TextBlock>
                </Expander.Header>
                <Expander.Style>
                    <Style TargetType="Expander">                          
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=Name}" Value="{x:Null}">
                                <Setter  Property="Visibility" Value="Collapsed"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Expander.Style>
            </Expander>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

<强> c#中

     public Window1()
    {
        InitializeComponent();
        List<HeaderList> lst = new List<HeaderList>();
        lst.Add(new HeaderList(){Name= "Header1"});
        lst.Add(new HeaderList() { Name = "Header2" });
        lst.Add(new HeaderList() { });
        lst.Add(new HeaderList() { Name = "Header4" });
        lst.Add(new HeaderList() { });
        lst.Add(new HeaderList() { });
        lst.Add(new HeaderList() { Name = "Header7" });
        this.DataContext = this;
        lstbx.ItemsSource = lst;     
    }
}
public class HeaderList
{
    public string Name { get; set; }
}

<强>结果

enter image description here

答案 1 :(得分:0)

使用绑定到Name属性到扩展器可见性和自己的转换器

        <Expander Visibility="{Binding Path=Name, Converter={StaticResource EmptyStringToVisibility}}">
             <Expander.Header>
                 <TextBlock Text="{Binding Path=Name}"/>
             </Expander.Header>
        </Expander>

转换器例如:

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

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