Right alignment of items in Windows.Forms.ListBox

↘锁芯ラ 提交于 2020-01-05 10:39:13

问题


Is there a proper way to align items to the right for ListBoxes from the .net Windows.Forms?

You can use

example_box = ListBox()
example_box.RightToLeft = RightToLeft.Yes

This enables the right alignment, but also prints your items right to left. Also the formatting does some really strange things here:

'% one two 4.72' gets displayed as 'one two 4.72 %'

For digits only this works quite well, but feels rather wonky. Are there better solutions?


回答1:


RightToLeft layout is meant for the Arabic and Hewbrew cultures, they write text right-to-left. It also affects how text is rendered, you found a side-effect. You need to use owner-draw to get it the way you want it. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form.

using System;
using System.Drawing;
using System.Windows.Forms;

class ReverseListBox : ListBox {
    public ReverseListBox() {
        this.DrawMode = DrawMode.OwnerDrawFixed;
    }
    protected override void OnDrawItem(DrawItemEventArgs e) {
        e.DrawBackground();
        if (e.Index >= 0 && e.Index < this.Items.Count) {
            var selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;
            var back = selected ? SystemColors.Highlight : this.BackColor;
            var fore = selected ? SystemColors.HighlightText : this.ForeColor;
            var txt = this.Items[e.Index].ToString();
            TextRenderer.DrawText(e.Graphics, txt, this.Font, e.Bounds, fore, back, TextFormatFlags.Right | TextFormatFlags.SingleLine);
        }
        e.DrawFocusRectangle();
    }
}



回答2:


I don't think there are any existing features of Windows Forms that will allow you to do this; you might have to override the control's drawing and draw the thing yourself.



来源:https://stackoverflow.com/questions/5341650/right-alignment-of-items-in-windows-forms-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!