3
我有一個自定義控件「託管」在自定義面板中(都是我的)。WPF MeasureOverride不適用於我的自定義控件
我的自定義面板有這樣的代碼:
protected override Size MeasureOverride(Size availableSize)
{
foreach (UIElement child in Children)
{
child.Measure(availableSize);
// Do stuff with the Desired Size. (This is an example)
resultSize.Width += child.DesiredSize.Width;
resultSize.Height = Math.Max(resultSize.Height, child.DesiredSize.Height);
}
//.. Other Measure Stuff
}
所有的標準控件我把我的面板做工精細。但我的自定義控件DesiredSize
設置爲非常小的寬度(5像素)。儘管它上面有一個Label
,它至少需要40個像素才能顯示。
所以我把這個代碼放到我的自定義控制:
protected override Size MeasureOverride(Size constraint)
{
var baseSize = base.MeasureOverride(constraint);
var labelTextWidth = GetStringWidth(label.Content.ToString(), label);
if (baseSize.Width == 0)
baseSize.Width = 100;
if (baseSize.Width < labelTextWidth)
baseSize.Width = labelTextWidth;
return baseSize;
}
這會返回一個Size
這是正確的。但在我的Panel的MeasureOverride中,child.DesiredSize並不反映我從我的子控件的MeasureOverride返回的內容。
任何想法爲什麼會這樣做?我能做些什麼來讓它將我計算的Measure正確地傳遞到面板上的DesiredSize中?(您不能只設置DesiredSize。)
請發佈您的自定義控件的模板,以及您在面板的measureoverride中作爲availableSize獲取的內容。 – AndrewS 2013-03-15 21:00:48
@AndrewS - 我的自定義面板的模板太大,無法在此處發佈(255行)。我在這裏加載它作爲要點:https://gist.github.com/Vaccano/5173613。 availableSize是{510,Infinity} – Vaccano 2013-03-15 22:25:08