Search code examples
wpfxamlbindingstackpanel

WPF binding mvvm StackPanel


I am beginner in wpf, and I have a problem with stackpanel binding. I have to dynamically generate labels, and add it to stackpanel. I had following code in .cs file:

    public DataImport()
    {
        labels.Add(new StringObject { Value = "tes" });
        labels.Add(new StringObject { Value = "tes2" });
        labels.Add(new StringObject { Value = "tes3" });
    }
    private ObservableCollection<StringObject> labels = new ObservableCollection<StringObject>();

    public ObservableCollection<StringObject> Labels
    {
        get { return labels; }
        private set
        {
            if (value == labels) return;
            labels = value;
            OnPropertyChanged("Labels");
        }
    }
    public class StringObject
    {
        public string Value { get; set; }
    }

Next in xaml I have:

<ItemsControl ItemsSource="{Binding Path=Labels}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Grid.Row="1" Height="237" HorizontalAlignment="Center" VerticalAlignment="Top" Width="186" FlowDirection="LeftToRight">
                <Label Content="{Binding Path=Value}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The real problem is that in xaml window I see only the first element from the labels object. Can u tell me what i did wrong ?

PS: my class DataImport of course inherits INotifyPropertyChanged


Solution

  • The ItemTemplate is per item. So just specify a label.

    <ItemsControl ItemsSource="{Binding Path=Labels}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding Path=Value}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>