Lio*_*fel 4 c# button backcolor winforms
我在Windows窗体中遇到C#按钮问题.
我以编程方式创建了许多按钮,然后将它们添加到表单中.
有趣的是,除了修改之外,对这些按钮(位置和大小)的每次修改BackColor
都很容易执行.只有按钮的颜色保持不变.
代码看起来像这样:
public class SimpleSortAlgDisplayer : ISortAlgDisplayer
{
#region ISortAlgDisplayer Member
void ISortAlgDisplayer.Init(int[] Data)
{
this.DataLength = Data.Length;
this.DispWin = new CurrentSortStateWin();
this.DispWin.Show();
this.DispWin.Size = new Size(60 + (10 * this.DataLength), 120);
this.myArrayElements = new Button[this.DataLength];
for (int i = 0; i < this.DataLength; i++)
{
this.myArrayElements[i] = new Button();
//begin of series of invoked actions
this.myArrayElements[i].Size=new Size(5,(int)(((80)*(double)Data[i])/1000));
this.myArrayElements[i].Location = new Point(30 + (i * 10), 90-(this.myArrayElements[i].Size.Height));
this.myArrayElements[i].Enabled = true;
this.myArrayElements[i].BackColor = Color.MidnightBlue;
this.myArrayElements[i].UseVisualStyleBackColor = true;
this.DispWin.Controls.Add(this.myArrayElements[i]);
this.myArrayElements[i].Refresh();
}
}
Run Code Online (Sandbox Code Playgroud)
想法有人吗?
Invoke
会给我一些DispWin
尚未创建的运行时错误.UseVisualStyleBackColor
为false不会改变任何内容BackColor
和/ ForeColor
或显示DispWin
也没有效果.我哪里错了?
您正在尝试设置颜色,但是然后您覆盖它说 UseVisualStyleBackColor = true
如果要使用自定义颜色,则需要设置UseVisualStyleBackColor
为false
或者鼠标悬停时颜色仅应用于按钮.
一个简单的测试上传到GitHub
public partial class mainForm : Form
{
Random randonGen = new Random();
public mainForm()
{
InitializeComponent();
}
private void mainForm_Load(object sender, EventArgs e)
{
populate();
}
private void populate()
{
Control[] buttonsLeft = createButtons().ToArray();
Control[] buttonsRight = createButtons().ToArray();
pRight.Controls.AddRange(buttonsRight);
pLeft.Controls.AddRange(buttonsLeft);
}
private List<Button> createButtons()
{
List<Button> buttons = new List<Button>();
for (int i = 1; i <= 5; i++)
{
buttons.Add(
new Button()
{
Size = new Size(200, 35),
Enabled = true,
BackColor = GetColor(),
ForeColor = GetColor(),
UseVisualStyleBackColor = false,
Left = 20,
Top = (i * 40),
Text = String.Concat("Button ", i)
});
}
return buttons;
}
private Color GetColor()
{
return Color.FromArgb(randonGen.Next(255), randonGen.Next(255), randonGen.Next(255));
}
}
Run Code Online (Sandbox Code Playgroud)
结果