【问题标题】:Ownerdrawn TreeView (WinForms)Ownerdrawn TreeView (WinForms)
【发布时间】:2014-04-18 09:56:50
【问题描述】:

我有一个带有复选框的 TreeView 控件,该控件完全由所有者绘制 (DrawMode = TreeViewDrawMode.OwnerDrawAll)。

我想要做的是绘制复选框所有者,以便它们可以具有灰色状态。我为此使用VisualStyleRenderer

当我必须将展开/折叠字形和复选框正确放置在项目边界中时,就会出现问题,因为字形和复选框的“命中测试区域”似乎都是未知且不可更改的。

有没有办法获得这些区域的边界,或者用自定义值替换默认值?

【问题讨论】:

  • 疯狂地yyyyyyyyyyyyyyyy

标签: c# winforms treeview custom-controls ownerdrawn


【解决方案1】:

我遇到了同样的问题。您必须将绘图偏移适当的量,这是可以预测的。

这里可能比您需要的更多,但这是我与日历控件一起使用的自定义树的绘图:

private void TreeViewControl_DrawNode(Object sender, DrawTreeNodeEventArgs e)
{
    //What might seem like strange positioning/offset is to ensure that our custom drawing falls in
    //  line with where the base drawing would appear.  Otherwise, click handlers (hit tests) fail 
    //  to register properly if our custom-drawn checkbox doesn't fall within the expected coordinates.

    Int32 boxSize = 16;
    Int32 offset = e.Node.Parent == null ? 3 : 21;
    Rectangle bounds = new Rectangle(new Point(e.Bounds.X + offset, e.Bounds.Y + 1), new Size(boxSize, boxSize));
    ControlPaint.DrawCheckBox(e.Graphics, bounds, e.Node.Checked ? ButtonState.Checked : ButtonState.Normal);
    if (e.Node.Parent != null)
    {
        Color c = Color.Black;
        String typeName = e.Node.Name.Remove(0, 4);
        Object o = Enum.Parse(typeof(CalendarDataProvider.CalendarDataItemType), typeName);
        if (o != null && (o is CalendarDataProvider.CalendarDataItemType))
            c = CalendarDataProvider.GetItemTypeColor((CalendarDataProvider.CalendarDataItemType)o);
        bounds = new Rectangle(new Point(bounds.X + boxSize + 2, e.Bounds.Y + 1), new Size(13, 13));
        using (SolidBrush b = new SolidBrush(c))
            e.Graphics.FillRectangle(b, bounds);
        e.Graphics.DrawRectangle(Pens.Black, bounds);
        e.Graphics.DrawLine(Pens.Black, new Point(bounds.X + 1, bounds.Bottom + 1), new Point(bounds.Right + 1, bounds.Bottom + 1));
        e.Graphics.DrawLine(Pens.Black, new Point(bounds.Right + 1, bounds.Y + 1), new Point(bounds.Right + 1, bounds.Bottom + 1));
    }
    Font font = new Font("Microsoft Sans Serif", 9f, e.Node.Parent == null ? FontStyle.Bold : FontStyle.Regular);
    bounds = new Rectangle(new Point(bounds.X + boxSize + 2, e.Bounds.Y), new Size(e.Bounds.Width - offset - 2, boxSize));
    e.Graphics.DrawString(e.Node.Text, font, Brushes.Black, bounds);
}

【讨论】:

  • 您好,感谢您的回复!实际上,现在我正在按照您的代码进行操作。我想知道 boxSizeoffset 值是否可以在运行时读取(即,使用某些 Win32 API),因为我担心将来这些值可能会改变,然后我的 UI 会以某种方式损坏......跨度>
  • 我离开它是因为我觉得它很安全。基本控件不太可能以这种方式更改,因为它是 Win32 的基础。你可能会得到它,但我怀疑这是否值得。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多