增加ListBox

时间:2018-05-26 16:22:18

标签: c# listbox

如何增加listbox1中的行间距;以及水平缩进每个字符串?

Form1中/ ListBox1中:
ListBox1

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        if (Properties.Settings.Default.Accounts == null)
            Properties.Settings.Default.Accounts = new List<Account>();

        if (Properties.Settings.Default.Accounts != null)
        {
            foreach (var account in Properties.Settings.Default.Accounts)
            {
                listBox1.Items.Add(account);
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        new Form2(listBox1).Show();
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedItem is Account selectedAccount)
        {
            textBox1.Text = selectedAccount.Name;
            textBox2.Text = selectedAccount.Login;
            textBox3.Text = selectedAccount.Password;
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (Properties.Settings.Default.Accounts != null)
            Properties.Settings.Default.Accounts.RemoveAt(listBox1.SelectedIndex);

        listBox1.Items.Remove(listBox1.SelectedItem);

        Properties.Settings.Default.Save();
    }


}

窗体2:
Form2

public partial class Form2 : Form
{
    private readonly ListBox _listBox;

    public Form2(ListBox listBox)
    {
        InitializeComponent();
        _listBox = listBox;
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        Account account = new Account
        {
            Name = textBox1.Text,
            Login = textBox2.Text,
            Password = textBox3.Text
        };

        _listBox.Items.Add(account);

        Properties.Settings.Default.Accounts.Add(account);

        Properties.Settings.Default.Save();

        Close();
    }
}

班级“帐户”:
Class "Account"

public class Account
{
    public string Name { get; set; }

    public string Login { get; set; }

    public string Password { get; set; }

    public override string ToString()
    {
        return $"{Name}";
    }
}

1 个答案:

答案 0 :(得分:0)

将此属性设置为true以告诉框架您将自己绘制它:

listBox1.DrawMode = DrawMode.OwnerDrawVariable;

然后处理MeasureItem事件并将LineHeight设置为适合您的内容:

private void ListBox1_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e)
{
    e.ItemHeight = 30; // or something else
}