ItemTemplate TextBlock problem

I am trying to create an element template where part of the field in the stack pane can be empty. When it's empty, I would like the visiblility to collapse. I tried putting triggers but it doesn't work and I'm not very familiar with this part of WPF.

Also, I would like to change the background color of this element when a certain value in my binding is true. It is the same?

Thank.

0


source to share


2 answers


Using the ViewModel is one approach to solving this problem.

If your data was stored in the Item class, you must make an ItemViewModel to wrap the item to display in the item control. The ViewModel class will implement the INotifyProperty modification to update the display, and the setters will raise the PropertyChanged event by passing the appropriate property name. You can also create property change events for as many related changed fields as possible.

Suppose you want Item.Description to appear in a collapsed field when Description is empty. ViewModel properties might look like:



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 XAML, bind the text property to Description and the Visibility property to DescriptionVisibility.

+1


source


If you want to hide an element if it is null, you need to override ControlTemplate

it ListBoxItem

(or ListViewItem

whatever, depending on which container you are using) and use triggers that target DataContext

, for example:

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

      

However, I suggest you use a delegate Filter

on yours CollectionView

to exclude your empty elements from your view directly to avoid dropping unused elements.



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

CollectionViewSource.GetDefaultView(yourCollection).Filter = o => o != null;

      

0


source







All Articles