Is there a way to refresh all bindings in WPF?

╄→尐↘猪︶ㄣ 提交于 2019-12-21 03:21:18

问题


If my code looks somewhat like the code beneath, would it be possible to refresh all bindings directly or would I have to hard-code all the bindings to refresh?

Service-side:

[ServiceContract]
public interface IMyServiceContract {
    [OperationContract]
    MyDataContract GetData();
}
[ServiceBehavior]
public class MyService {
    [OperationBehavior]
    public MyDataContract GetData() {
        MyDataContract data = new MyDataContract();
        data.val1 = "123";
        data.val2 = "456";
        return data;
    }
}
[DataContract]
public class MyDataContract {
    [DataMember]
    public string val1;
    public string val2;
}

Client-side xaml (namespace boilerplate code omitted):

<Window x:Class="MyWindow" DataContext="{Binding RelativeSource={RelativeSource Self}}" Title="{Binding Path=val1, Mode=OneWay}">
    <DockPanel>
        <TextBlock Text="{Binding Path=val1, Mode=OneWay}"/>
        <TextBlock Text="{Binding Path=val2, Mode=OneWay}"/>
    </DockPanel>
</Window>

Client-side code-behing:

public partial class MyWindow {
    MyServiceClient client = new MyServiceClient();
    MyDataContract data;
    public string val1 {get{return data.val1;}}
    public string val2 {get{return data.val2;}}
    DispatcherTimer updateTimer = new DispatcherTimer();

    public MyWindow() {
        timer.Interval = new TimeSpan(0, 0, 10);
        timer.Tick += new EventHandler(Tick);
        Tick(this, null);
        timer.Start();
        InitializeComponent();
    }

    void Tick(object sender, EventArgs e) {
        data = client.GetData();
        // Refresh bindings
    }
}

Please disregard any coding standards violations in the example code since it is simply intended as an example for the intended use.


回答1:


Found the answer, seems like that calling PropertyChanged with the PropertyChangedEventArgs property name set to "" refreshes all bindings.
The DataContext changing worked too, although this felt a bit "cleaner".




回答2:


You can null then re-set the DataContext of the parent object.

DataContext = null;
DataContext = data;



回答3:


How about making "data" a dependency property. Binding your DataContext to that will make your bindings update when you re-assign "data".



来源:https://stackoverflow.com/questions/5157068/is-there-a-way-to-refresh-all-bindings-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!