Skip to main content
Home Forums Silverlight Programming Programming with .NET - General Update ListBox Dynamically when underlying data changed
4 replies. Latest Post by esite on July 3, 2009.
(0)
esite
Participant
754 points
195 Posts
07-02-2009 6:27 AM |
A rookie question here I am sure. I adapted this tutorial as an example (http://silverlight.net/learn/tutorials/databinding.aspx).
When I delete a record from the bound data of ListBox the list box is not updated. I have no idea how to make it change it's datasource once it is deleted.
So I adapted the tutorial to have a delete chapter button like this and the Listbox to bind TwoWay:
<
I would expect or know how to be able to update the Listbox immediately once I click delete the Chapter.
Any help would be greatly appreciated.
Thanks.
varshavmane
Contributor
6263 points
1,489 Posts
07-02-2009 7:01 AM |
Use ObservableCollection.
Have a quick look around - see if this link helps...
HTH
HarshBar...
Star
9908 points
1,719 Posts
07-02-2009 7:14 AM |
I had modified few things in your sample.
You can try this.
//Xaml file
<Canvas x:Name="LayoutRoot" Background="White"> <ListBox x:Name="Chapters" ItemsSource="{Binding User, Mode=TwoWay}" VerticalAlignment="Bottom" HorizontalAlignment="Left" Height="350" Width="200" Grid.Row="2" Grid.Column="1" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding UserName, Mode=TwoWay}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <Button Grid.Row="5" Grid.Column="1" Canvas.Left="250" Canvas.Top="30" x:Name="btnDeleteList" Content="Delete Chapter" Click="btnDeleteList_Click" Height="30" Width="100" /> </Canvas>
//Code behind:
public partial class Page : UserControl { ObservableCollection users; public Page() { InitializeComponent(); users = new ObservableCollection(); users.Add(new User() { UserName = "Harsh" }); users.Add(new User() { UserName = "Nimesh" }); users.Add(new User() { UserName = "Test" }); users.Add(new User() { UserName = "Test1" }); users.Add(new User() { UserName = "Test2" }); Chapters.ItemsSource = users; } private void btnDeleteList_Click(object sender, RoutedEventArgs e) { if (users.Count > 2) { users.RemoveAt(2); } } } public class User: INotifyPropertyChanged { private string username ; public string UserName { get { return username ; } set { username = value; onPropertyChanged( this , "UserName" ) ; } } public event PropertyChangedEventHandler PropertyChanged ; private void onPropertyChanged( object sender , string propertyName) { if ( this.PropertyChanged != null ) { PropertyChanged(sender, new PropertyChangedEventArgs(propertyName)) ; } } }
It uses observable collection concept.
07-02-2009 7:55 AM |
Thanks varshavmane and HarshBardhan the key is that ObservableCollection. Appreciate your efforts.
07-03-2009 5:31 AM |