2013-08-19 38 views
0

我需要在頁面1中填充一個組合框,其中包含在MainWindow頁面中保存的另一個組合框中所選名稱的地址詳細信息。我嘗試了下面的代碼,但MainWindow中的組合框名稱無法識別。在wpf中綁定兩個頁面

主窗口:

private void displayParts() 
    { 
     try 
     { 
      sc.Open(); 
      string Query = "select * from Parts"; 
      SqlCommand createCommand = new SqlCommand(Query, sc); 
      SqlDataReader dr = createCommand.ExecuteReader(); 
      while (dr.Read()) 
      { 
       string Name = dr.GetString(1); 

       cbParts.Items.Add(Name);//Displaying a list in the Combo Box 
      } 
      sc.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

第1頁:

private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e) 
    {    
     string constring = "Data Source=.;Initial Catalog=**.MDF;Integrated Security=True"; 
     DataContext=MainWindow. 
     string Query = "select * from Partners where Name='" + cbParts.SelectedItem.ToString() + "' ;"; 
     SqlConnection conDataBase = new SqlConnection(constring); 
     SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase); 
     SqlDataReader myReader; 

     try 
     { 


      sc.Open(); 
      myReader = cmdDataBase.ExecuteReader(); 
      if (myReader.Read()) 
      { 
       txtPartner.Text = myReader["Name"].ToString(); 
      } 

      myReader.Close(); 


      sc.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 
+0

你在這裏遇到的異常是什麼?第1頁中的 –

+0

cbParts無法識別 - 「cbParts在當前上下文中無法識別。」 – user2631662

回答

0
// may need to cast this to your MainWindow's type 
var mainWindow = Application.Current.MainWindow; 

//... 

mainWindow.cbParts.Items.Add(Name); 

此外,您可以將您的組合框綁定到ObservableCollection財產,並添加項目到集合中。