【问题标题】:C# "Controls" Does Not Exist in The Current ContextC#“控件”在当前上下文中不存在
【发布时间】:2015-03-17 13:09:21
【问题描述】:

错误

在我的应用程序中,我尝试使用“Controls.Add”,但 Visual Studio 不断给我错误:

"错误 1 ​​当前上下文中不存在名称 'Controls' C:\Users\Admin\Desktop\Demo\Demo\MainWindow.xaml.cs 42 13 Demo"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }



        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Window1 window = new Window1();
            Button button = new Button();

            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            button.Content = "New Button";
            button.Visibility = Visibility.Visible;
            button.Height = 50;
            button.Width = 200;


            Controls.add(button); <-- ERROR IS FOUND HERE


            window.Show();


        }
    }
}

我正在使用来自 WinForms 的 WPF。任何建议表示赞赏,谢谢。

【问题讨论】:

  • button.Name = "button"

标签: c# wpf


【解决方案1】:

您需要按照以下方式做一些事情:

var window = new Window1();

var stackPanel = new StackPanel { Orientation = Orientation.Vertical };

Button button = new Button();
button.Content = "New Button";
button.Visibility = Visibility.Visible;
button.Height = 50;
button.Width = 200;

stackPanel.Children.Add(button);

window.Content = stackPanel;
window.Show();

不过,我建议在 XAML 中定义所有 UI 组件并阅读 MVVM 模式。

【讨论】:

    【解决方案2】:
     <StackPanel Name=“splMain“>
    <Button Name=“btnAddMore“ Click=“btnAddMore_Click“>Add Another</Button>
    

    还有按钮点击:

    System.Windows.Controls.Button newBtn = new Button();
      newBtn.Content = “A New Button”;
      splMain.Children.Add(newBtn);
    

    【讨论】:

      【解决方案3】:
       Button SaveButton = new Button();
       SaveButton.Name = "Save";
       SaveButton.Content = "Save";
       Grid1.Children.Add(SaveButton);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-06
        • 2014-12-09
        • 1970-01-01
        • 1970-01-01
        • 2018-03-21
        相关资源
        最近更新 更多