-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,然后向网格添加两个按钮,之后我尝试将 b2.Content 属性与 b1.Content 绑定,我的预期结果是运行后,b2.Content 将显示为“Hello ",但是运行后,b2.Content 是空的,为什么?

谢谢。

4

1 回答 1

0

在您的代码中,您可以使用Binding.Source实际的 b1 按钮而不是Binding.ElementName其名称:

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

不知道为什么 ElementName 不起作用。它可能与 XAML 之间的差异Name有关x:Name,这是您通常使用 ElementName 绑定的地方。

在 WPF 中,x:Name 和 Name 属性有什么区别?

于 2013-04-10T09:07:20.557 回答