使用代码创建窗口时,WPF绑定不起作用

时间:2013-04-10 07:44:03

标签: c# wpf binding

任何人都可以帮我解释为什么这段代码不起作用:

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

感谢。

1 个答案:

答案 0 :(得分:0)

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

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

不确定为什么ElementName不起作用。它可能与XAML中Namex:Name之间的区别有关,这是您通常使用ElementName绑定的地方。 / p>

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