AgainMe AgainMe - 3 months ago 13
C# Question

Hide item if binded value is null?

I've a

ListBox
like this:

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


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

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


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

Event: foo


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

UPDATE:

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

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


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?

Answer

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

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