2013-07-01 116 views
0

我在将项目添加到ItemsControl时遇到问题。 这是我的XAML页面:将项目动态添加到ItemsControl中

<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中,其他人不会出现。 那么有人知道问题在哪里?

+0

什么事件?它何时被触发?什么是“记录”类型,它在哪里定义? – PoweredByOrange

回答

2

您需要声明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() }); 
} 
+0

非常感谢。它工作得很好。但请向我解释ObservableCollection和List在这个问题上的区别(因为我在我的方法中使用了List),为什么将它分配给构造器中的Itemsource而不是方法中,即使它们都给出了同样的重击。 非常感谢你的帮助。 –

+0

'ObservableCollection'是一个带有通知机制的列表。如果您使用经典列表,ItemsControl将无法知道您已向集合中添加了新元素(除非您手动指定)。我在构造函数中设置了'ItemsSource'属性,因为你只需要做一次。它可以在任何地方,只是构造函数是一个方便的地方,以确保只执行一次。 –

+0

Okey我明白。非常感谢你 –