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?

SomeBody
  • 7,515
  • 2
  • 17
  • 33

1 Answers1

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.

dotnetzen
  • 166
  • 1
  • 9