0

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

Emond
  • 50,210
  • 11
  • 84
  • 115
Karol_P
  • 265
  • 1
  • 3
  • 10
  • It looks like you're creating one StackPanel per item in your ItemsControl. Is there a reason you're not just binding a ListBox to your Labels collection? – AndrewS May 30 '12 at 23:56
  • Yes, I can't use ListBox becouse this will be mapping from file fields to database files. This labels are only for user information what he will map. – Karol_P May 30 '12 at 23:58
  • @AndrewS I change my xaml and it works. You was right ;) Thanks ;) – Karol_P May 31 '12 at 00:00

1 Answers1

3

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>
Emond
  • 50,210
  • 11
  • 84
  • 115