【问题标题】:Adding Children to StackPanel in Parent Window from UserControl in WPF/C#从 WPF/C# 中的 UserControl 将子项添加到父窗口中的 StackPanel
【发布时间】:2014-03-23 05:40:01
【问题描述】:

我有一个 MainWindow,在这个 MainWindow 中我加载了一个 UserControl。 MainWindow 包含一个 StackPanel。现在我想从 UserControl 向 StackPanel 添加一个按钮。

如果我直接添加它,它可以工作(来自 MainWindow)——但不能来自 UserControl。

例子:

MainWindow.xaml.cs

    public MainWindow()
    {
        InitializeComponent();

        var myTestRadioButton = new RadioButton
        {
            Name = "TestRadioButton",
            Height = 31.5,
            Width = 140,
        };

        MyStackPanel.Children.Add(myTestRadioButton);
    }

作品

UserControl1.xaml.cs

    public UserControl1()
    {
        InitializeComponent();

        var parentWindow = new MainWindow();

        var myTestRadioButton = new RadioButton
        {
            Name = "TestRadioButton",
            Height = 31.5,
            Width = 140,
        };

        parentWindow.MyStackPanel.Children.Add(myTestRadioButton);
     }

没用。

我也尝试过创建父窗口的静态实例...

有趣的是 -> 我没有收到错误消息或类似的东西......它只是不起作用(例如按钮不显示......)

请帮忙 :) :) :)

【问题讨论】:

  • 不要在 WPF 的过程代码中创建或操作 UI 元素。这就是 XAML 的用途。
  • 最好的方法是为您的用户控件创建一个事件,在您的父表单中订阅它并在那里完成您的工作。
  • 那我将如何在 XAML 中解决这个问题?
  • 问题是——我想用创建的 buttons(如浏览器中的标签)来实现像标签控件(但带有按钮)这样的行为——但按钮是在主窗口中,它们的内容在 UserControl 中 - 但我仍然想像标签一样切换 ^^

标签: c# wpf xaml user-controls


【解决方案1】:

这样做var parentWindow = new MainWindow(); 您正在用户控件中创建new window,而不是对当前 MainWindow 的引用

public UserControl1()
        {
            InitializeComponent();

            var parentWindow = new MainWindow();

            var myTestRadioButton = new RadioButton
            {
                Name = "TestRadioButton",
                Height = 31.5,
                Width = 140,
            };
         //just add something like this  
        public  void AddChildControl(Window MyWindow)
       {
              MyWindow.MyStackPanel.Children.Add(myTestRadioButton);
       }

     }

从用户控件更改主窗口

public MainWindow()
    {
        InitializeComponent();

        var myTestRadioButton = new RadioButton
        {
            Name = "TestRadioButton",
            Height = 31.5,
            Width = 140,
        };

            var usercontrol1= new    UserControl1() ; 
             usercontrol.AddChildControl(this);

    }

【讨论】:

    【解决方案2】:

    你创建了一个新的窗口实例。 (K B 的回答)这无论如何都行不通

    如果你真的(无论如何)需要动态 GUI,你应该使用另一种方法:

    你可能想在你的用户控件中有一个堆栈面板

    <Stackpanel x:Name="myStack"/>
    

    代码隐藏:

    Usercontrol()
    {
    myStack.Children.Add(new WhateverControl());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      • 2013-11-24
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多