将项动态添加到ItemsControl

本文关键字:ItemsControl 添加 动态 | 更新日期: 2023-09-27 18:20:48

我在向ItemsControl添加项时遇到问题。这是我的XAML页面:

<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>

在我后面的代码中,我有一个事件。

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

所有变量都已定义。

问题是,当事件被多次触发时,只有第一次被添加到ItemsControl中,其他的不会出现。有人知道问题出在哪里吗?

将项动态添加到ItemsControl

您需要将records声明为ObservableCollection。将其一次性分配给列表框的ItemsSource属性,然后仅使用您的集合。例如,在调用InitializeComponents方法之后,可以在页面的构造函数中执行此操作:

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() });
}