0

作为在 ListBox 中为文本着色的尝试,我发现了本指南C#:更改列表框项目颜色(我在 Visual Studio 2012 上使用 Windows 窗体应用程序)。代码正在工作,但问题是我想在从右到左模式下使用文本框,但是当我在 ListBox 设置中更改它时它不起作用,所以我假设它需要以某种方式在代码中更改,这就是我需要你帮助的原因。非常感谢你!阿隆

4

2 回答 2

1

您的 y 位置为 0,因此每次插入消息时它都位于左侧。要将其放在右侧,您需要重新计算位置。

看下面的例子。

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem
    if (item != null)
    {
        e.Graphics.DrawString( // Draw the appropriate text in the ListBox
                   item.Message, // The message linked to the item
                   listBox1.Font, // Take the font from the listbox
                   new SolidBrush(item.ItemColor), // Set the color 
                   width - 4, // X pixel coordinate
                   e.Index * listBox1.ItemHeight,
                   new StringFormat(StringFormatFlags.DirectionRightToLeft)); // Y pixel coordinate.  Multiply the index by the ItemHeight defined in the listbox.                
    }
    else
    {
        // The item isn't a MyListBoxItem, do something about it
    }
}
于 2012-08-17T12:33:52.077 回答
0

列表框本身是左对齐的,您无法在 UIR 编辑器中更改它。您可以在创建要传递给列表框的字符串时应用适当的对齐元素:请参阅InsertListItem函数的项目标签参数的在线帮助。所有转义码都将应用于您插入到列表框中的每一行;无法将默认格式样式应用于控件。

于 2012-08-17T14:20:24.103 回答