Search code examples
c#wpfbindingobservablecollectiontextblock

Binding all elements of ObservableCollection to TextBlock


I am trying to bind a TextBlock to items in a ObservableCollection. TextBlock values should be generated up to elements from collection. Count of elements in collection is between 0 and 7 (if it helps). MyClass implemented INotifyPropertyChanged. It should be directly TextBlock, not ListBox. How can I do it? Thanks!
Update: The problem is that I don't know previously the number of elements in collection. I know that it is better to use ListBox or ListView in this case, but it's important to make it in TextBlock or Label

For example:

  1. ObservableCollection contains elements 0, 1, 2.
    TextBlock should contains following "Values: 0, 1, 2"

  2. ObservableCollection contains elements 0, 1.
    TextBlock should contains following "Values: 0, 1"

    <TextBlock>
           <Run Text="Values: "/>
           <Run Text="{Binding Values}" />                 
    </TextBlock>
    

ObservableCollection<int> values = new ObservableCollection<int>();
        public ObservableCollection<int> Values
        {
            get => values;
            set
            {
                values = value;
                OnPropertyChanged();
            }
        }

Solution

  • Use a Converter that concat those strings:

    public class StringsCollectionConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return null;
            return string.Join("\n", value as ObservableCollection<string>);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Xaml

    <Window.Resources>
        <local:StringsCollectionConverter x:Key="StringsCollectionConverter"/>
    </Window.Resources> 
    <Grid>
        <TextBlock Text="{Binding TextBlockCollection, Converter={StaticResource StringsCollectionConverter}}"></TextBlock>
    </Grid>