0
我有一个带有标签的主窗口。WPF BindingExpression UpdateSource不工作
<Label
Name="RoundLabel"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Content="{Binding Source={x:Static core:Supervisor.Simulator}, Path=Round, UpdateSourceTrigger=Explicit, Mode=TwoWay}"
/>
在代码背后,是更新lablecontent
public void updateRound()
{
BindingExpression binding = RoundLabel.GetBindingExpression(Label.ContentProperty);
binding.UpdateSource();
}
在另一大类的方法我称之为updateRound
public int Round
{
get
{
return round.Value;
}
set
{
if (!(round.Value == value))
{
round.Value = value;
App.Current.Dispatcher?.Invoke(() => (App.Current.MainWindow as MainWindow).updateRound());
}
}
所以每次的一轮的变革应该是值在标签中更改。 没有例外,但GUI中的roundnumber不是updatet。
我的错误在哪里?有没有错过?
public class Simulator : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int round;
public int Round
{
get
{
return round;
}
set
{
if (round != value)
{
round = value;
PropertyChanged?.Invoke(
this, new PropertyChangedEventArgs(nameof(Round)));
}
}
}
}
现在把你的模拟类的实例到窗口的DataContext
,并绑定:
'UpdateTarget()'应该可以工作......但它确实不是**您在wpf UI中进行更新的方式。 'INotifyPropertyChanged'是你的朋友 – ASh
显然你并没有理解数据绑定是如何工作的,尤其是如何改变源属性通知绑定更新其目标属性。 Binding.UpdateSource()不是你需要的。相反,在拥有源属性的类中实现INotifyPropertyChanged接口。开始阅读这里:[数据绑定概述](https://msdn.microsoft.com/en-us/library/ms752347(v = vs.110).aspx)。 – Clemens
谢谢,UpdateTarget()的作品。我也尝试过INotifyPropertyChanged,但是在updateSourceTrigger中遇到了一些问题... – Voovo