2013-04-10 122 views
-2

誰能幫我爲什麼這個代碼不工作,創建窗口:WPF綁定不工作時使用代碼

private void button2_Click(object sender, RoutedEventArgs e) 
    { 
     BuildMainWindow().Show(); 
    } 

    private Window BuildMainWindow() 
    { 
     Window w = new Window(); 
     w.BeginInit(); 

     System.Windows.Controls.Grid g = new System.Windows.Controls.Grid(); 
     g.BeginInit(); 
     System.Windows.Controls.RowDefinition r1 = new System.Windows.Controls.RowDefinition(); 
     r1.Height = new GridLength(1, GridUnitType.Star); 
     System.Windows.Controls.RowDefinition r2 = new System.Windows.Controls.RowDefinition(); 
     r2.Height = new GridLength(1, GridUnitType.Star); 
     g.RowDefinitions.Add(r1); 
     g.RowDefinitions.Add(r2); 

     System.Windows.Controls.Button b1 = new System.Windows.Controls.Button(); 
     b1.BeginInit(); 
     b1.Name = "b1"; 
     b1.Content = "Hello"; 
     Grid.SetRow(b1, 0); 
     b1.EndInit(); 

     System.Windows.Controls.Button b2 = new System.Windows.Controls.Button(); 
     b2.BeginInit(); 
     b2.Name = "b2"; 
     b2.Content = "World"; 
     Grid.SetRow(b2, 1); 
     b2.EndInit(); 

     g.Children.Add(b1); 
     g.Children.Add(b2); 
     g.EndInit(); 

     w.Content = g; 
     w.EndInit(); 

     System.Windows.Data.Binding bind = new System.Windows.Data.Binding("Content"); 
     bind.ElementName = "b1"; 
     b2.SetBinding(System.Windows.Controls.ContentControl.ContentProperty, bind); 

     return w; 
    } 

在這裏,我試圖創建一個窗口對象,然後加網格,然後添加兩個按鈕到電網,在此之後,我嘗試將b2.Content屬性與b1.Content綁定,我的預期結果是在運行後,b2.Content將顯示爲「Hello」,但運行後,b2.Content僅爲空,爲什麼?

謝謝。

回答

0

在你的代碼,你可以在實際B1按鈕使用Binding.Source而不是Binding.ElementName它的名字:

//bind.ElementName = "b1"; 
bind.Source = b1; 

不知道爲什麼的ElementName不工作,但..它可能有一些做的XAML中的Namex:Name之間的差異,這是您通常使用ElementName綁定的位置。

In WPF, what are the differences between the x:Name and Name attributes?

+0

謝謝,這個作品做。奇怪的部分是,如果我創建XAML(而不是通過代碼創建Window實例)並將綁定代碼放入事件處理程序中,則一切正常。這讓我覺得,也許我忘記了構建窗口部分的東西。 – lugionline 2013-04-10 10:08:33

+0

謝謝,我最終通過使用FrameworkElement.RegisterName將每個控件名稱註冊到窗口實例來修復它。感謝您的幫助,關於x:Name and Name的鏈接確實有所幫助。 – lugionline 2013-04-10 10:49:55

+0

酷,我不知道的.RegisterName方法:) – Sphinxxx 2013-04-10 10:59:02