0

I have a Listview that's ItemSource is bound to a ObservableCollection and that's SelectedItem is bound to a string. It is possible that the observable collection contains an empty string; in that case, I want the listview to display some special string instead of just an empty item without text.

This is how I imagine it should work:

<ListView ItemSource="{Binding AvailableTags}" SelectedItem="{Binding SelectedTag}">
<ListView.ItemContainerStyle>
     <Style TargetType="ListViewItem">
          <Setter Property="Content" Value="Untagged" />
              <Style.Triggers>
                   <DataTrigger Binding="-> Which binding to use?" Value="">
                       <Setter Property="Content" Value="-> How to get the Default value?" />
                   </DataTrigger>
              </Style.Triggers>
     </Style>
</ListView.ItemContainerStyle>
</ListView>

As you can see, in this dummy source code, there are two place holders. How can I make it working? Or am I on the wrong track?

1
  • Show your viewmodel code. Is AvailableTags a ObservableCollection<string>? Commented Nov 13, 2017 at 17:23

1 Answer 1

1

You can modify the ListView ItemTemplate, and use an IValueConverter as such:

<ListView 
        ItemsSource="{Binding AvailableTags}" 
        SelectedItem="{Binding SelectedTag}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Converter={StaticResource TagConverter}}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

The converter:

public class TagConverter : IValueConverter
{
    #region IValueConverter Members

    object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string tag = (string)value;

        return string.IsNullOrEmpty(tag) ? "Your custom string display" : tag;
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

Remember to add the converter as a resource in scope.

Sign up to request clarification or add additional context in comments.

2 Comments

This helped. I tried it with a converter first, but added it to <ListView ItemsSource="...">, hence it tried to convert the complete ObservableCollection<string>.
Glad it helped!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.