【问题标题】:WPF binding not work when create window using code使用代码创建窗口时 WPF 绑定不起作用
【发布时间】:2013-04-10 07:44:03
【问题描述】:

谁能帮我弄清楚为什么这段代码不起作用:

    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 是空的,为什么?

谢谢。

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 谢谢,这确实有效。奇怪的是,如果我创建 XAML(而不是通过代码创建 Window 实例)并将绑定代码放在事件处理程序中,一切正常。这让我觉得也许我忘记了构建窗口部分中的某些内容。
    • 谢谢,我终于通过使用 FrameworkElement.RegisterName 将每个控件名称注册到窗口实例来修复它。感谢您的帮助,关于 x:Name 和 Name 的链接真的很有帮助。
    • 酷,我不知道 .RegisterName 方法:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    相关资源
    最近更新 更多