-2

このコードが機能しない理由を誰か助けてもらえますか:

    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 を追加し、グリッドに 2 つのボタンを追加しようとしました。この後、b2.Content プロパティを b1.Content にバインドしようとしました。実行後、b2.Content は「Hello」と表示されます。 」ですが、実行後、b2.Content が空になっているのはなぜですか?

ありがとう。

4

1 に答える 1