2017-05-30 68 views
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,並綁定:

+0

'UpdateTarget()'應該可以工作......但它確實不是**您在wpf UI中進行更新的方式。 'INotifyPropertyChanged'是你的朋友 – ASh

+2

顯然你並沒有理解數據綁定是如何工作的,尤其是如何改變源屬性通知綁定更新其目標屬性。 Binding.UpdateSource()不是你需要的。相反,在擁有源屬性的類中實現INotifyPropertyChanged接口。開始閱讀這裏:[數據綁定概述](https://msdn.microsoft.com/en-us/library/ms752347(v = vs.110).aspx)。 – Clemens

+0

謝謝,UpdateTarget()的作品。我也嘗試過INotifyPropertyChanged,但是在updateSourceTrigger中遇到了一些問題... – Voovo

回答

0

通知WPF綁定更改的源屬性值通常是通過實現INotifyPropertyChanged接口這樣做標籤的Content這樣的:

<Window ...> 
    <Window.DataContext> 
     <local:Simulator/> 
    </Window.DataContext> 
    <Grid> 
     <Label Content="{Binding Round}"/> 
    </Grid> 
</Window> 

落後於DataContext的訪問對象在代碼中設置屬性:

((Simulator)DataContext).Round = 42;