Fly_federer
Fly_federer

Reputation: 206

binding a listbox with List<string> inside a ObservableCollection

I have a problem with a binding on an List inside an ObservableCollection.

this is my XAML :

        <ListBox Background="Black" x:Name="Test" ItemsSource="{Binding Items}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Foreground="Red" Text="{Binding tags}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

This is my ObservableCollection.

    public ObservableCollection<ArticleJSON> Items { get; private set; }

This is my class ArticleJSON :

public class ArticleJSON
{

    public string content { get; set; }
    public List<string> tags { get; set; }
}

My list tags isn't empty. If i bind on "content" it's work perfectly... I hope someone can help me

Upvotes: 0

Views: 1053

Answers (2)

puko
puko

Reputation: 2980

  <Grid>
        <ListBox Background="Black" 
                 x:Name="Test" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ListBox Foreground="Red" ItemsSource="{Binding tags}" >
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding}" Foreground="Red" Height="40"></TextBlock>
                            </DataTemplate>
                          </ListBox.ItemTemplate>
                    </ListBox>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>

Upvotes: 0

iJay
iJay

Reputation: 4293

You cannot directly bind List<string> to a Text block. Convert your List to a single string and bind it. to do that you can try a value converter.

<TextBlock Text="{Binding Path=tags,Converter={StaticResource ListToStringConverter}}"/>

code behind,

[ValueConversion(typeof(List<string>), typeof(string))]
public class ListToStringConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (targetType != typeof(string))
            throw new InvalidOperationException("The target must be a String");
        // strings are joining with a comma, you can use what you prefer 
        return String.Join(", ", ((List<string>)value).ToArray());
    }

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

Upvotes: 1

Related Questions