开发者

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 li开发者_运维知识库ke 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.


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜