如何在C#中使用命令Controls.Add() [英] How to use the command Controls.Add() in C#
本文介绍了如何在C#中使用命令Controls.Add()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我是C#的新手,并且一直在尝试实现按钮的非常基本的动态编程.
我在Google上寻找解决方案,但我不断收到此错误:
Hi everybody,
I am a newbie with c# and have been trying to implement a very basic dynamic programming of a button.
I googled to look for a solution, but I keep obtaining this error:
'System.Windows.Controls.WrapPanel' does not contain a definition for 'Controls' and no extension method 'Controls' accepting a first argument...
如果不使用此 Controls.Add()函数,我无法弄清楚如何在窗口上显示按钮.
我想念什么?
感谢您的帮助!
I cannot figure out how to have the button showing up on my window without using this Controls.Add() function.
What am I missing?
Thanks for your help!
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Simple_Button_Feedback
{
public partial class MainWindow : Window
{
public MainWindow()
{
CreateButton();
InitializeComponent();
}
private void CreateButton()
{
Button b = new Button();
b.Content = "I'm a silly Button";
b.Click += new RoutedEventHandler(this.ButtonClick);
b.Height = 25;
b.Width = 100;
// b.Location = new Point(50,50);
LinearGradientBrush lgb = new LinearGradientBrush();
lgb.GradientStops.Add(new GradientStop(Colors.Yellow, 0));
lgb.GradientStops.Add(new GradientStop(Colors.Green, 1));
b.Background = lgb;
// this.Controls.Add(b);
// A <WrapPanel> named "Panel1" is defined in the .xaml file
Panel1.Controls.Add(b);
}
protected void ButtonClick(object sender, EventArgs e)
{
MessageBox.Show("Click me again. That felt good.");
}
}
}
推荐答案
不知道为什么删除了您的解决方案,但供以后参考:
Not sure why your solution was deleted but for future reference:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Simple_Button_Feedback
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CreateButton();
}
private void CreateButton()
{
Button b = new Button();
b.Content = "I'm a silly Button";
b.Click += new RoutedEventHandler(this.ButtonClick);
b.Height = 25;
b.Width = 100;
// b.Location = new Point(50,50);
LinearGradientBrush lgb = new LinearGradientBrush();
lgb.GradientStops.Add(new GradientStop(Colors.Yellow, 0));
lgb.GradientStops.Add(new GradientStop(Colors.Green, 1));
b.Background = lgb;
// this.Controls.Add(b);
// A <WrapPanel> named "Panel1" is defined in the .xaml file
Panel1.Children.Add(b);
}
protected void ButtonClick(object sender, EventArgs e)
{
MessageBox.Show("Click me again. That felt good.");
}
}
}
,您可以使用此代码动态添加按钮.
you can use this code to add button dynamically.
private void CreateButton()
{
Button Button1 = new Button();
Button1.Name = "Button1";// this is useful to identify the object
Button1.Location = new Point(25, 25);
this.Controls.Add(Button1);
}
这篇关于如何在C#中使用命令Controls.Add()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文