Techee
Techee

Reputation: 1825

How to force a WPF binding to refresh?

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?

Upvotes: 136

Views: 169080

Answers (5)

blindmeis
blindmeis

Reputation: 22445

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));

Upvotes: 64

dotNET
dotNET

Reputation: 35400

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();

Upvotes: 44

Kushal Waikar
Kushal Waikar

Reputation: 2994

Try using BindingExpression.UpdateTarget()

Upvotes: 6

Egemen Çiftci
Egemen Çiftci

Reputation: 744

MultiBinding friendly version...

private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
    BindingOperations.GetBindingExpressionBase((ComboBox)sender, ComboBox.ItemsSourceProperty).UpdateTarget();
}

Upvotes: 10

brunnerh
brunnerh

Reputation: 184441

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.

Upvotes: 236

Related Questions