c# – 有没有办法刷新WPF中的所有绑定?

如果我的代码看起来像下面的代码,是否可以直接刷新所有的绑定,或者我必须硬编码所有的绑定来刷新?

服务端:

[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;
}

客户端xaml(省略命名空间样板代码):

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

客户端代码抖动:

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
    }
}

请忽略示例代码中的任何编码标准违规,因为它只是作为预期用途的示例.

找到答案,好像调用PropertyChanged的PropertyChangedEventArgs属性名设置为“”刷新所有的绑定. DataContext变化也是如此,虽然这感觉有点“更干净”了.
相关文章
相关标签/搜索