-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僅爲空,爲什麼?
謝謝。
謝謝,這個作品做。奇怪的部分是,如果我創建XAML(而不是通過代碼創建Window實例)並將綁定代碼放入事件處理程序中,則一切正常。這讓我覺得,也許我忘記了構建窗口部分的東西。 – lugionline 2013-04-10 10:08:33
謝謝,我最終通過使用FrameworkElement.RegisterName將每個控件名稱註冊到窗口實例來修復它。感謝您的幫助,關於x:Name and Name的鏈接確實有所幫助。 – lugionline 2013-04-10 10:49:55
酷,我不知道的.RegisterName方法:) – Sphinxxx 2013-04-10 10:59:02