0

我想将 UI 元素添加到 Winforms 中的 ListBox。当我添加一个椭圆或一个矩形时 - 我在列表中得到的是 Object.ToString()。当我将 UI 元素插入 ListBox.Items 时,如何获得 WPF 的行为 - 我将看到我插入的对象而不是它的字符串表示形式?

4

1 回答 1

1

一个起点是声明一个适合做绘制形状所需的接口。您的具体 Shape 类应该实现该接口:

    public interface IShape {
        Rectangle Measure();
        void Draw(Graphics g);
        // etc...
    }

您应该将 ListBox 的 DrawMode 属性设置为 DrawMode.OwnerDrawVariable。这需要您实现其 MeasureItem 事件处理程序,需要确定列表框项应该有多大才能显示形状:

    void listBox1_MeasureItem(object sender, MeasureItemEventArgs e) {
        e.ItemWidth = listBox1.ClientSize.Width;
        var shape = listBox1.Items[e.Index] as IShape;
        if (shape != null) e.ItemHeight = shape.Measure().Height;
    }

并且您需要为 DrawItem 事件实现一个事件处理程序来绘制形状:

    void listBox1_DrawItem(object sender, DrawItemEventArgs e) {
        e.DrawBackground();
        var shape = listBox1.Items[e.Index] as IShape;
        if (shape != null) shape.Draw(e.Graphics);
        e.DrawFocusRectangle();
    }
于 2013-10-20T12:10:43.807 回答