谁能帮我弄清楚为什么这段代码不起作用:
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;
}
这里我尝试创建一个 Window 对象,然后添加 Grid,然后向网格添加两个按钮,之后我尝试将 b2.Content 属性与 b1.Content 绑定,我的预期结果是运行后,b2.Content 将显示为“Hello ",但是运行后,b2.Content 是空的,为什么?
谢谢。