.NET|--Winform|--DotnetBar库的Button显示顺序设置
前言
winform真的要注意细节啊.细节拉满才能把握得住的一个框架.
需求
实现一个动态添加按钮, 但是要根据按钮来排序 .
解决方案
using DevComponents.DotNetBar;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
private List<Control> _controlList = new List<Control>();
private readonly static int _tabWidth = 45;
private readonly static int _tabHeight = 45;
private readonly static Size s_btnDefaultSize = new System.Drawing.Size(_tabWidth, _tabHeight);
public Form1()
{
InitializeComponent();
this.StartPosition = FormStartPosition.Manual;
var b3 = AddBtn("3", 3);
var b1 = AddBtn("1", 1);
var b2 = AddBtn("2", 2);
this.Controls.Add(b3);
this.Controls.Add(b1);
this.Controls.Add(b2);
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
_controlList = _controlList.OrderBy(c => c.TabIndex).ToList();
var v = _controlList.Select(s => new { name = s.Name, tab = s.TabIndex });
for (int i = 0; i < _controlList.Count; i++)
{
_controlList[i].Location = new Point(0, _tabHeight * (i + 1));
}
}
protected override void OnControlAdded(ControlEventArgs e)
{
base.OnControlAdded(e);
_controlList.Add(e.Control);
this.Height += _tabHeight;
}
ButtonX AddBtn(string name, int index)
{
ButtonX newBtnTab = new ButtonX();
newBtnTab.Name = name;
newBtnTab.Text = name;
newBtnTab.TabIndex = index;
newBtnTab.Click += NewBtnTab_Click;
newBtnTab.Size = s_btnDefaultSize;
newBtnTab.Cursor = Cursors.Hand;
newBtnTab.Location = new Point(_tabWidth, _tabHeight);
newBtnTab.BackColor = System.Drawing.Color.FromArgb(255, 251, 251, 251);
newBtnTab.ColorTable = DevComponents.DotNetBar.eButtonColor.Flat;
return newBtnTab;
}
private void NewBtnTab_Click(object? sender, EventArgs e)
{
var newIndex = _controlList.Count + 1;
var newBtn = AddBtn(newIndex.ToString(), newIndex);
this.Controls.Add(newBtn);
}
}
}