【问题标题】:How do I add UI Children to an empty WPF-Page?如何将 UI 子项添加到空的 WPF 页面?
【发布时间】:2016-02-23 04:20:38
【问题描述】:

我有一个 MainWindow,它是一个 NavigationWindow。在这个 MainWindow 中,我想切换几个页面。页面之一必须由代码而不是 XAML 动态生成。当我之前有一个普通的窗口时,我可以添加这样的 UI 组件:

Button b = new Button();
b.Content = "Hello";
this.AddChild(b);

或者,如果我首先使用此方法添加(例如)一个 StackPanel,我可以使用以下方法将 Children 添加到此 StackPanel:

myPanel.Children.Add(b);

但是,页面类没有 Children 属性或 AddChild 方法。 到目前为止我发现的唯一方法是:

AddVisualChild(b);

页面显示,但我没有看到我使用此方法添加的任何组件。 那么如何正确地将子项添加到 WPF 页面?

【问题讨论】:

    标签: c# wpf user-interface wpf-controls


    【解决方案1】:

    首先,Window.AddChild 在向它添加多个对象时会抛出异常,因为WindowContentControlPage 只允许 1 个孩子。所以您使用 Page.Content 属性设置孩子。因此,您想将一个容器添加到您的 Page,然后将子代添加到该容器中。
    例如:

    Button b = new Button();
    b.Content = "Hello";
    StackPanel myPanel = new StackPanel();
    myPanel.Children.Add(b);
    this.Content = myPanel;
    

    【讨论】:

    • 非常感谢,没想到内容属性会对此负责。
    【解决方案2】:

    我不确定这是否适合您,但您可以尝试将页面内容设置为用户控件。例如。使用 StackPanel 并将所有孩子添加到其中。之后将Page 的内容设置为Stackpanel

    这是 MainWindow 的构造函数中的一个惰性示例。

    public MainWindow()
    {
        InitializeComponent();
    
        StackPanel panel = new StackPanel();
        Button b1 = new Button {Content = "Hello"};
        Button b2 = new Button {Content = "Hi"};
    
        panel.Children.Add(b1);
        panel.Children.Add(b2);
    
        Page page = new Page {Content = panel};
    
        this.Content = page;
    }
    

    【讨论】:

    • 好吧,我不够快 :)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    相关资源
    最近更新 更多