Hey all, I’m writing a windows phone application in silverlight, and I’m trying to dynamically update the source of a DataTemplate I have in place. Here’s the xaml that I have:
<ListBox Grid.Row="1" Height="607" HorizontalAlignment="Left" Name="listBox1" VerticalAlignment="Top" Width="480">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<StackPanel Width="370">
<TextBlock Text="{Binding Transcription}" Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Duration}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
In the C# behind it, I pass the data along in the main init function like so:
list.Add(new NoteToSelf { Transcription = "oh hi", Duration = "9001 seconds" });
list.Add(new NoteToSelf { Transcription = "fgsfds", Duration = "$Texas seconds" });
listBox1.ItemsSource = list;
Where list is a List collection. All this works great – the hardcoded data is displayed as expected on screen. However, when I try to dynamically update the information, it silently fails. If I bind an action to a button that runs this code:
list.Add(new NoteToSelf { Transcription = "FFUUUUUUUU", Duration = "LISTBOX, Y U NO UPDATE?" });
listBox1.ItemsSource = list;
I would expect it to add a new element to the collection, reassign the source for the DataTemplate, then update the screen with the new data. This however is not the case. How would I go about doing this?
Obviously this is POC code that is simply a means to an end, I’m just looking to get elements to dynamically update at the moment. Also, I may very well be approaching this in the wrong way, if there is a better way to dynamically add elements on the screen from a template it would be immensely helpful to hear them.
Thanks all.
You didn’t state what type list was, but I’m going to assume its a plain List<>. In order to update the UI, it needs to have some sort of notification mechanism. The framework supports this through INotifyPropertyChanged. You can implement INotifyPropertyChanged on your databound class, and manually update as you add, or use a container that implements it. The easiest approach is to replace your List<> with an ObservableCollection<>.