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

本文关键字:WPF 绑定 工作 代码 创建 窗口 | 更新日期: 2023-09-27 18:08:18

谁能告诉我为什么这个代码不工作:

    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。内容属性与b1。内容,我的预期结果是运行后,b2。内容将显示为"Hello",但运行后,b2。内容是空的,为什么?

谢谢。

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

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

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

不知道为什么ElementName不工作虽然…这可能与XAML中Namex:Name之间的差异有关,这是您通常使用ElementName绑定的地方。

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