AgainMe AgainMe - 1 month ago 11x
C# Question

Hide item if binded value is null?

I've a

like this:

<ListBox VerticalAlignment="Stretch"
ItemsSource="{Binding EventInfo}">

inside it I've a
with a list of TextBlock:

<ColumnDefinition Width="100"/>
<ColumnDefinition Width="20"/>
<TextBlock Text="Event:" FontWeight="Bold" Grid.Column="0" Grid.Row="0"/>
<TextBlock Text="{Binding Name}" FontWeight="Bold" Grid.Column="1" Grid.Row="0"/>

what I need to do is hide the textblock when for example, the binded value is
. I've associate this stuff:

Event: foo

but in some case the
is null, I need to hide both
and the binded, is possible do this?


I'm trying to do this pure in xaml as:

<Style TargetType="TextBlock">
<Trigger Property="Text" Value="">
<Setter Property="Visibility" Value="Collapsed" />
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed" />

The problem's that the application fall in interruption mode and as xaml error I get:

System.Windows.Data Error: 40 : BindingExpression path error: 'Name' property not found on 'object' ''Style' (HashCode=7)'.

this error is repeated for each textblock that I've what am I doing wrong?


You can bind the visibility to a property

 Visibility="{Binding IsVisibleName, Converter={StaticResource myBoolToVisibilityConverter}}

through a static bool converter

 <local:BooleanToVisibiltyConverter x:Key="myBoolToVisibilityConverter" />

for all the elements that must/can be hidden.

Then converter transforms true into visible

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       bool isVisible = (bool)value;
       return (isVisible ? Visibility.Visible : Visibility.Collapsed);

Then you'll set them when the conditions are met, like for example (this is a general idea, I don't know about your specific details) in the Name setter (and you have to configure all the other triggers as well)

 public string Name {
   get { return name;}
   set { 
      name = value; OnPropertyChanged("Name");
      IsVisibleName = name != null; IsVisibleEvent = event != null && name != null;

In pure XAML there are data triggers

            <DataTrigger Binding="{Binding SomeValue}" Value=" x:Null ">
                <Setter Property="Visibility" Value="Visible"/>