简体   繁体   English

如何强制刷新 WPF 绑定?

[英]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?加载组合框后,有什么方法可以刷新此绑定?

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.但是正如 Blindmeis 指出的那样,您还可以触发更改通知,如果您的集合实现INotifyCollectionChanged (例如在ObservableCollection<T>中实现),它将同步,因此您不需要执行任何操作。

if you use mvvm and your itemssource is located in your vm.如果您使用 mvvm 并且您的 itemssource 位于您的虚拟机中。 just call INotifyPropertyChanged for your collection property when you want to refresh.当您想要刷新时,只需为您的集合属性调用 INotifyPropertyChanged。

OnPropertyChanged(nameof(YourCollectionProperty));

添加我的 2 美分,如果你想用你的 Control 的新值更新你的数据源,你需要调用UpdateSource()而不是UpdateTarget()

((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();

MultiBinding friendly version... MultiBinding 友好版本...

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

尝试使用BindingExpression.UpdateTarget()

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) (Windows 10,UWP)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM