views:

203

answers:

2

Hi,

i am trying to make an item template where some of the field in my stack panel can be empty. When it's empty, I would like to set the visiblility to collapsed. I tried putting triggers but it doesn't seem to work and I am not very familiar with this part of WPF

Also, I would like to change the color of the background of this item when a specific value in my binding is true. Is it the same thing?

Thanks.

A: 

If you want to hide an item if it's content is null, you have to redefine the ControlTemplate of its ListBoxItem (or ListViewItem or something else depending on which item container you're using) and use triggers that target the DataContext, like:

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

However, I'd suggest that you use the Filter delegate on your CollectionView to exclude your empty items from your view directly, to avoid collapsing unused items.

For example to exclude null objects, in your code behind, use:

CollectionViewSource.GetDefaultView(yourCollection).Filter = o => o != null;
Julien Lebosquain
The thing is I don't want to hide the whole item, just a part of the item template that is empty on some occasion.
David Brunelle
+1  A: 

Using a ViewModel is one approach to solving this kind of problem.

The if your data was stored in an Item class you would make an ItemViewModel to wrap the Item for display in your items control. The ViewModel class would implement INotifyProperty changed in order to update the display and the setters would raise the PropertyChanged event passing the appropriate property name. You can also raise property changed events for as many interrelated changed fields as necessary.

Suppose you wanted Item.Description to display in a collapsed field when Description is empty. Your ViewModel properties could look like this

public string Description
{
    get { return mItem.Description; }
    set { mItem.Description = value; Notify("Description"); Notify("DescriptionVisibility"); }
}

public Visibility DescriptionVisibility
{
    get { return string.IsNullOrEmpty(mItem.Description) ? Visibility.Visible : Visibility.Collapsed; }
}

In the XAML bind the text property to Description and the Visibility property to DescriptionVisibility.

Doug Ferguson
I like this idea. Since I use custom item, I could easily define new properties that read-only and define that info. Thanks
David Brunelle