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?
-
1What do you mean by simple binding? Normally when you use binding the control should automatically refresh.– EmondApr 15, 2011 at 13:14
-
14Techee, no offence, but I believe H.B. deserves his answer to be accepted ;-)– DaniMay 20, 2014 at 8:56
-
2@Dani I'm not sure Techee is ever coming back - six and a half years since he's been logged in– The Lonely CoderOct 5, 2017 at 16:28
5 Answers
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.
-
-
1@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?– H.B.Jul 4, 2016 at 15:31
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));
-
10
-
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 Aug 18, 2017 at 18:18
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();
}