How to force a WPF binding to refresh?

C#WpfData Binding

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

MultiBinding friendly version...

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

Solution 5 - C#

Try using BindingExpression.UpdateTarget()

Solution 6 - C#

I was fetching data from backend and updated the screen with just one line of code. It worked. Not sure, why we need to implement Interface. (windows 10, UWP)

    private void populateInCurrentScreen()
    {
        (this.FindName("Dets") as Grid).Visibility = Visibility.Visible;
        this.Bindings.Update();
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTecheeView Question on Stackoverflow
Solution 1 - C#H.B.View Answer on Stackoverflow
Solution 2 - C#blindmeisView Answer on Stackoverflow
Solution 3 - C#dotNETView Answer on Stackoverflow
Solution 4 - C#Egemen ÇiftciView Answer on Stackoverflow
Solution 5 - C#Kushal WaikarView Answer on Stackoverflow
Solution 6 - C#ItzdspView Answer on Stackoverflow