如果我的代码看起来有点像下面的代码,是否可以直接刷新所有绑定,还是我必须硬编码所有绑定才能刷新?
服务侧:
[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>
客户端代码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
}
}
请忽略示例代码中的任何编码标准违规行为,因为它只是作为预期用途的示例。
答案 0 :(得分:28)
找到答案,似乎调用PropertyChanged并将PropertyChangedEventArgs属性名设置为""
刷新所有绑定。
DataContext的更改也起作用,虽然这感觉有点“干净”。
答案 1 :(得分:21)
您可以为null,然后重新设置父对象的DataContext。
DataContext = null;
DataContext = data;
答案 2 :(得分:0)
如何使“数据”成为依赖属性。将DataContext绑定到那将使您的绑定在重新分配“数据”时更新。