2014-02-12 79 views
0

我想綁定一個字符串屬性以顯示在我的狀態欄中,如果我的數據庫已連接。下面的代碼:將字符串屬性綁定到狀態欄文本

C#

public class TimeBase : INotifyPropertyChanged 
{ 
    private DXTickDB db; 
    string[] args = new string[] { }; 

    public event PropertyChangedEventHandler PropertyChanged; 
    private bool isTBconnected; 
    public string connectionStatus { get; set; } 

    public bool tb_isconnected 
    { 
     get { return isTBconnected; } 
     set 
     { 
      if (value != isTBconnected) 
      { 
       isTBconnected = value; 

       if(isTBconnected == false) 
       { 
        connectionStatus = "TimeBase is not connected"; 
       } 
       else 
       { 
        connectionStatus = "TimeBase is connected"; 
       } 

       OnPropertyChanged("connectionStatus"); 
      } 
     } 
    } 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 


    #region TimeBase Connection 

    public void ConnectToTimeBase() 
    { 
     if (args.Length == 0) 
      args = new string[] { "not available for security reasons" }; 

     db = TickDBFactory.createFromUrl(args[0]); 
     try 
     { 
      db.open(true); 
      tb_isconnected = true; 
     } 
     catch 
     { 
      tb_isconnected = false; 
     } 

    } 
    #endregion 

這是XAML中在我的主窗口中的狀態欄:

 <StatusBar Height="23" DockPanel.Dock="Bottom" Background="Green"> 
     <StatusBarItem> 
      <StackPanel Orientation="Horizontal"> 
       <TextBlock 
        Foreground="{StaticResource Foreground}" 
        Text="{Binding Path=connectionStatus}"> 
       </TextBlock> 
      </StackPanel> 
     </StatusBarItem> 
    </StatusBar> 

我試圖將其綁定到字符串屬性connectionStatus但沒有文本出現,即使當我調試時,我可以看到connectionStatus更新。對這裏有什麼問題有什麼建議?

+0

你設置你的窗口的DataContext的? – user1064519

+0

我不認爲我該怎麼做? @ user1064519 – kknaguib

+0

請看我的回答 – user1064519

回答

2

DataContext屬性應該包含您的模型,像這樣:

TimeBase timeBaseInstance; 
    public MainWindow() 
    { 
     timeBaseInstance = new TimeBase(); 

     //Set the dataContext so bindings can iteract with your data 
     DataContext = timeBaseInstance; 
     InitializeComponent(); 
    } 
+0

謝謝! @ user1064519 – kknaguib

相關問題