2

I have a TextBlock as follow:

<TextBlock Text="You don't have any more items." Visibility="{binding}"

and in code behind I defined a Stack called items as follow:

private Stack<Item> _items;

How do I bind the text visibility in xaml to visible when _item.Any is false?

iamsharp
  • 39
  • 6

2 Answers2

1

There are several steps to achieving what you want to do and they are all described here

You need to create a value converter similar to this;

public class EmptyCollectionToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var collection = (Stack<int>) value;
        return collection.Any() ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Then you need to add a reference to is in your resource dictionary in your xaml like this;

 <views:EmptyCollectionToVisibilityConverter x:Key="EmptyCollectionToVisibilityConverter"/>

Finally bind your property in your view model to the visibility of your control and give the binding the converter like this;

Visibility="{Binding Items, Converter={StaticResource EmptyCollectionToVisibilityConverter}}"

Your property will probably need to be an observableCollection (which will mean changing the value converter example I gave you slightly.

mark_h
  • 5,233
  • 4
  • 36
  • 52
  • I think I might stick with textBlock.Visibility = Visibility.Visible after calling pop and set it back collapsed it after calling push. I thought that xaml binding will provide a better and simple solution but I was wrong. Thank you for the solution – iamsharp May 19 '16 at 16:13
0

I'd probably go with:

private Stack<Item> _items;
// bind to this property using converter
public bool IsVisible => !(_items?.Any(...) ?? false);

You shouldn't expose your _stack directly, but e.g. use methods to do something (because you need to rise notification every time you push/pop an item):

public void PushItem(Item item)
{
    _items.Push(item);
    OnPropertyChanged(nameof(IsVisible)); // implement INotifyPropertyChanged
}
Sinatr
  • 20,892
  • 15
  • 90
  • 319
  • So what is the xaml binding sytax for IsVisible? – iamsharp May 19 '16 at 16:03
  • @iamsharp, [look here](http://stackoverflow.com/q/7000819/1997232). If you don't care about MVVM principles, then you can simply use `Visibility` type instead or `bool` (return `Visibility.Visible` instead of `true` and e.g. `Visibility.Collapsed` otherwise). In this case you don't need converters. Note: converters are mean to be reusable, if you are making converter which is not used anywhere else you have chosen a sub-optimal solution. – Sinatr May 20 '16 at 07:11