InvalidateVisual

时间:2018-03-01 16:54:46

标签: c# wpf

我有从Grid扩展的自定义网格,它为覆盖的OnRender方法中的每个网格单元格添加边框。问题是我的网格是动态的,因此列数和行数会改变运行时。在检测到ViewModel的数量更改后,我设法更改了RowDefinitions和ColumnDefinitions的数量。添加新的网格行和列后,我通过调用网格上的InvalidateVisual和UpdateLayout强制重绘,这会强制重新调用重写的OnRender方法。但是在屏幕上我仍然看到旧网格边界不是新网格。这是OnRender方法。

protected override void OnRender(DrawingContext dc)
{
    double leftOffset = 0;
    double topOffset = 0;
    Pen pen = new Pen(Brushes.Black, 3);
    Pen darkPen = new Pen(Brushes.Black, 6);
    pen.Freeze();
    darkPen.Freeze();

    foreach (RowDefinition row in this.RowDefinitions)
    {
        dc.DrawLine(pen, new Point(0, topOffset), new Point(this.ActualWidth, topOffset));
        topOffset += row.ActualHeight;
    }
    // draw last line at the bottom
    dc.DrawLine(pen, new Point(0, topOffset), new Point(this.ActualWidth, topOffset));

    foreach (ColumnDefinition column in this.ColumnDefinitions)
    {
        dc.DrawLine(darkPen, new Point(leftOffset, 0), new Point(leftOffset, this.ActualHeight));
        leftOffset += column.ActualWidth;
    }
    //draw last line on the right
    dc.DrawLine(darkPen, new Point(leftOffset, 0), new Point(leftOffset, this.ActualHeight));

    base.OnRender(dc);
} 

我是WPF的新手,所以我不确定为什么视图没有更新。我不确定我做错了。我调试了这个方法,并确保在更新后调用此方法时,我有正确数量的行和列定义。这是网格更新后的图片,但边框位于旧地方

Border in wrong place

0 个答案:

没有答案