Reputation: 4897
I'm using a ListBox control with an ItemTemplate like so:
<ListBox Name="lbItemsList" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ID}" Padding="5,0,0,0" />
<TextBlock Text=" - " Padding="5,0,0,0" />
<TextBlock Text="{Binding Description}" Padding="5,0,0,0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Then, in the code I dynamically bind a collection to the ListBox like so:
lbItemssList.ItemsSource = _itemsList.Values;
But at times I need to rebind a different or modified list of items to the ListBox. When I do this, the ListBox doesn't update with the new list and it seems that the binding doesn't work correctly, unless I do this:
lbItemssList.ItemsSource = null;
lbItemssList.ItemsSource = _itemsList.Values;
I've done the same thing with other ListBox controls and not had this problem. What am I missing here?
Upvotes: 1
Views: 760
Reputation: 189437
First of all there is no "bind" here, you have simply assigned a collection to the ItemsSource
property.
The ItemsSource
property will compare the value assigned to it with the current value, if the value is the same it will do nothing.
My guess is your Values
property is not a ObservableCollection
(in which case the ListBox would track collection changes without you having to anything). Also whilst you may have changed the content of the Values
collection it remains the same instance of the collection originally assigned to the ItemsSource
.
Upvotes: 1
Reputation: 3679
i have tired that at my side and its working fine. My Code
public MainPage()
{
InitializeComponent();
BindData();
}
private void BindData()
{
List<MyClass> listClass = new List<MyClass>();
for (int i = 0; i < 20; i++)
{
MyClass aMyClass = new MyClass();
aMyClass.Description = "Description " + i.ToString();
aMyClass.ID = i;
listClass.Add(aMyClass);
}
lbItemsList.ItemsSource = listClass;
}
private void buttonaa_Click(object sender, RoutedEventArgs e)
{
List<MyClass> listClass = new List<MyClass>();
for (int i = 20; i < 40; i++)
{
MyClass aMyClass = new MyClass();
aMyClass.Description = "Description " + i.ToString();
aMyClass.ID = i;
listClass.Add(aMyClass);
}
lbItemsList.ItemsSource = null;
lbItemsList.ItemsSource = listClass;
}
<ListBox Name="lbItemsList" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ID}" Padding="5,0,0,0" />
<TextBlock Text="{Binding Description}" Padding="5,0,0,0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Do check if you are geting the same recored from databse and you are thinking that list is no refreshing
Upvotes: 0