I have got a combo box with items source attached using simple binding. Is there any way to refresh this binding once combo box is loaded?
How to force a WPF binding to refresh?
Asked Answered
What do you mean by simple binding? Normally when you use binding the control should automatically refresh. –
Barneybarnhart
Techee, no offence, but I believe H.B. deserves his answer to be accepted ;-) –
Pitchford
@Pitchford I'm not sure Techee is ever coming back - six and a half years since he's been logged in –
Plast
I don't really understand what is being asked. Is the entire collection being changed? Only its contents? What type of collection is being used? There is not enough detail. –
Haematinic
You can use binding expressions:
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
((ComboBox)sender).GetBindingExpression(ComboBox.ItemsSourceProperty)
.UpdateTarget();
}
But as Blindmeis noted you can also fire change notifications, further if your collection implements INotifyCollectionChanged
(for example implemented in the ObservableCollection<T>
) it will synchronize so you do not need to do any of this.
Doesn't seem to do a thing for me using a ListBox. –
Thun
@JonathanWood: Well, i cannot divine what kind of code you have, including what your binding looks like. Does the binding even work in the first place? –
Saxton
if you use mvvm and your itemssource is located in your vm. just call INotifyPropertyChanged for your collection property when you want to refresh.
OnPropertyChanged(nameof(YourCollectionProperty));
This is the cleanest approach imho. –
Tripetalous
This should be done where possible, but it should be noted it's not always practical. For instance if you're binding to a serial port, and want to check whether it's open, closed, the baud rate, etc you can create a wrapper class around the serial port that implements
INotifyPropertyChanged
, but you will have to keep the port private to that wrapper and thus need to write a property and method for everything on that port you use elsewhere in the project to ensure that the properties you are interested in notifying on always go through the wrapper –
Emmert Point to Note : This will not update the UI when there is an item added or removed from list. For this scenario you have to use observable collection –
Denbrook
if you call OnPropertyChanged(nameof(YourCollectionProperty)); after adding or removing an item - it works. but you are right observable collection to this build in. –
Quiteri
To add my 2 cents, if you want to update your data source with the new value of your Control, you need to call UpdateSource()
instead of UpdateTarget()
:
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();
MultiBinding friendly version...
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
BindingOperations.GetBindingExpressionBase((ComboBox)sender, ComboBox.ItemsSourceProperty).UpdateTarget();
}
© 2022 - 2024 — McMap. All rights reserved.