WPF控件DesiredSize在添加子控件和测量后不会改变

本文关键字:控件 改变 测量 DesiredSize 添加 WPF | 更新日期: 2023-09-27 18:05:53

我有一个wpf控件,我想在可能的多个页面上打印的行。我目前正在做的是一个接一个地添加每一行,看看它们对当前页面来说是否太大。如果是,则创建新页面控件的新版本,并开始向其添加行。

然而,在我向控件添加一行并调用Measure之后,我注意到控件的DesiredSize。高度还是一样的。我以前在一个silverlight应用程序中使用过这种技术,它在检测对页面来说太大的控件时效果很好。

Size measureSize = new Size(printDlg.PrintableAreaWidth,  double.PositiveInfinity);
//tripList is what I want the control to display
while (_rowIndex < tripList.Count)
{
    //add child element
    controlToPrint.AddRow(tripList[_rowIndex]);
    //re-measure
    controlToPrint.Measure(measureSize);
    //Do we go into the next page?
    if (controlToPrint.DesiredSize.Height > printDlg.PrintableAreaHeight)
    {
        //Create new page
    }
    ++_rowIndex
}

WPF控件DesiredSize在添加子控件和测量后不会改变

我猜你是在使用ListView:

int StopIndex;
double hgt = 0.0;
for(int i = 0; i< tripList.Count; i++){
controlToPrint.AddRow(tripList[i]);
hgt += controlToPrintf.Items[i].Height; //You didn't mentioned what control you are using, so I guess it's a ListView
if(hgt > controlToPrintf.Height) {
controlToPrint.RemoveRow(tripList[i]); //Remove last ítem that caused rows exced the control's height
StopIndex = --i; //Store the index of the item the control didn't allowed more rows to be added.
break;
}
}

如果手动设置高度,则可以检测控件中有多少行:

//Guessing you want a 50 pixel height row:
for(int i=0; i<(int)ControlToPrint.Height/50; i++){ //controlToPrintf.Height/50 rows can be added here 
controlToPrint.AddRow(triplist[i]);
controlToPrintf.Items[i].Height = 50;
}