Ayoub.A
Ayoub.A

Reputation: 2093

Dynamically adding items to an ItemsControl

I'm having a problem with adding items to an ItemsControl. This is my XAML page:

<ScrollViewer  Grid.Row="4">
    <ItemsControl Name="items">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                    <StackPanel Name="ContentControl">
                        <Canvas Name="canvas1" Height="60" VerticalAlignment="Top">
                            <TextBlock Text="{Binding RecordedTime}" Canvas.Left="10" Canvas.Top="7" Width="370"  FontSize="36"/>
                            <Controls:RoundButton Name="save" Canvas.Left="380" Height="58" Canvas.Top="6" />
                        </Canvas>
                    </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</ScrollViewer>

In my code behind I have an Event inside of it.

records.Add(new item { Item = date.Now.ToString() });

        items.ItemsSource = records; 

All the variables are already defined.

the problem is that when the event is triggered many times, only the first time is added to the ItemsControl, others do not appear. So does anyone know where is the problem?

Upvotes: 2

Views: 3494

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39007

You need to declare records as an ObservableCollection. Assign it once and for all to the ItemsSource property of the listbox, then use only your collection. You can do that for instance in the constructor of the page, after calling the InitializeComponents method:

public ObservableCollection<item> Records { get; set; }

// Constructor
public Page3()
{
    InitializeComponent();

    this.Records = new ObservableCollection<item>();

    this.items.ItemsSource = this.Records;
}

public void AddItem()
{
    // Thanks to the ObservableCollection,
    // the listbox is notified that you're adding a new item to the source collection,
    // and will automatically refresh its contents
    this.Records.Add(new item { Item = DateTime.Now.ToString() });
}

Upvotes: 4

Related Questions