Search code examples
wpftextblockitemtemplate

Problem with ItemTemplate TextBlock


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.


Solution

  • 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.