2016-11-08 51 views
0

我有一堆textboxes我想綁定到我的viewmodel中的字符串。我以爲我已經正確設置了所有內容,但是沒有任何內容出現在文本框中。文本框沒有正確綁定

這是我的XAML和我試圖綁定的文本框之一。

<Window x:Class="Server.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
     xmlns:l="clr-namespace:Server" 
     xmlns:viewmodel="clr-namespace:Server.ViewModels" 
     Title="MainWindow"> 
    <Window.DataContext> 
     <viewmodel:MainWindowViewModel /> 
    </Window.DataContext> 

    <TextBlock Name="ShipLatTB" 
      FontSize="17" 
      Text="{Binding Path=CurrentShipLat, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 

這裏的視圖模型:

namespace Server.ViewModels 
{ 
    class MainWindowViewModel : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 

     private string _currentShipLat; 
     public string CurrentShipLat 
     { 
      get { return _currentShipLat; } 
      set { _currentShipLat = value; OnPropertyChanged("CurrentShipLat"); } 
     } 

     // Create the OnPropertyChanged method to raise the event 
     protected void OnPropertyChanged(string name) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
      { 
       handler(this, new PropertyChangedEventArgs(name)); 
      } 
     } 
} 

我測試設置,以確保數據實際上是在「_currentShipLat」這等於命令「測試」,和調試,以驗證它。不知道還有什麼錯誤?

注:該文本框應該能夠動態更新。

編輯:如何給出downvote和投票結束的理由?這對任何人都沒有幫助。

+2

您是否在WPF窗口初始化後設置了字段_currentShipLat?這樣WPF永遠不會「看到」這個改變,因爲它不會觸發屬性改變的事件。 要麼確保在窗口初始化之前設置了字段,要麼使用屬性的setter而不是直接設置字段。 –

+0

你可以發佈你的TextBlock所在的xaml嗎?我加載了你的解決方案,對我而言,這些值正確填充。 –

+0

@NathanSwannet你是對的!我在初始化之後設置它,所以我必須使用setter屬性。現在一切正常。如果你想把這個作爲答案,我會標記它。 – pfinferno

回答

1

確保在WPF窗口初始化之前設置字段_currentShipLat。

如果你在窗口初始化之後執行它,WPF將永遠不會「看到」這個改變,因爲它不會觸發屬性改變的事件。要麼確保在窗口初始化之前設置了字段,要麼使用屬性的setter而不是直接設置字段。