1

我有一个像这样的视图树观察器:

rowsContainerVto = rowsContainerView.ViewTreeObserver;
rowsContainerVto.GlobalLayout += RowsContainerVto_GlobalLayout;

void RowsContainerVto_GlobalLayout (object sender, EventArgs e)
{
    if(rowsContainerVto.IsAlive)
        rowsContainerVto.GlobalLayout -= RowsContainerVto_GlobalLayout;

    vW = rowsContainerView.Width;
    Console.WriteLine ("\r now width is " + vW);
}

它应该做的是在布局视图后找到宽度,它做得很好。我只是不知道如何阻止它一遍又一遍地运行。

以上基本上是基于提出的建议。这只会使应用程序崩溃。当我摆脱“IsAlive”时,循环将永远继续。在第一次绘制和布局之后,我似乎无法找到阻止它的方法。

4

1 回答 1

0

由于您的 EventHandler 是匿名的,因此您无法再次取消订阅它,因为您没有对它的引用。

如果您想保持在同一范围内,可以执行以下操作:

EventHandler onGlobalLayout = null;
onGlobalLayout = (sender, args) =>
{
    rowsContainerVto.GlobalLayout -= onGlobalLayout;
    realWidth = rowsContainerView.Width;
}
rowsContainerVto.GlobalLayout += onGlobalLayout;

或者,您可以将 EventHandler 作为一种方法:

private void OnGlobalLayout(sender s, EventArgs e)
{
    rowsContainerVto.GlobalLayout -= OnGlobalLayout;
    realWidth = rowsContainerView.Width;
}

rowsContainerVto.GlobalLayout -= OnGlobalLayout;

这只是意味着rowsContainerVto并且realWidth必须是类成员变量。

于 2017-02-16T13:36:57.390 回答