如何获取堆栈面板的实际当前高度?
你好,
我想在 WPF 中制作一个自定义堆栈面板,它将根据面板高度自动将其子级调整为特定大小。但面板的高度是动态的,因为它会延伸到他的父级。当我想获取高度时(我尝试了所有可能性,请参阅代码),它始终为 0 或未定义,尽管在构建解决方案中它绝对不是 0。 代码如下:
XAML:
代码隐藏:
public class AutoSizeButtonStackPanel : StackPanel
{
public void AddChild(Button newButton)
{
double getPanelHeight;
getPanelHeight = this.ActualHeight; //is 0
getPanelHeight = this.ViewportHeight; //is 0
getPanelHeight = this.Height; //is n. def.
getPanelHeight = this.DesiredSize.Height; //is 0
getPanelHeight = this.RenderSize.Height; //is 0
newButton.Height = getPanelHeight / 2;
this.Children.Add(newButton);
}
}
Hallo,
i want to make a custom stackpanel in WPF, which shall automatically resizes his childs to a certain size depending on the panels height. But the panels height is dynamic because it stretches to his parent. When i want to get the height (i tried all possibilities, see code), it is always 0 or not defined, although in the build solution it is definitely not 0.
Here's the code:
XAML:
<my:AutoSizeButtonStackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
Code-Behind:
public class AutoSizeButtonStackPanel : StackPanel
{
public void AddChild(Button newButton)
{
double getPanelHeight;
getPanelHeight = this.ActualHeight; //is 0
getPanelHeight = this.ViewportHeight; //is 0
getPanelHeight = this.Height; //is n. def.
getPanelHeight = this.DesiredSize.Height; //is 0
getPanelHeight = this.RenderSize.Height; //is 0
newButton.Height = getPanelHeight / 2;
this.Children.Add(newButton);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能与您实际查询
this.ActualHeight
的时间有关。当调用AddChild()
时,高度实际上可能仍然为 0,因为 测量通道和安排通道可能尚未完成。所有影响孩子的尺寸和布局的事情都应该在 MeasureOverride 和 ArrangeOverride您应该看看如何编写自定义面板。关于这个主题有大量的资源。我个人认为这个是一个很好且简单的足够的教程。
This might have to do with when you actually query
this.ActualHeight
. At the timeAddChild()
is called the height really might still be 0 because the measure pass and the arrange pass might not have been through yet. Everything that affects the measure and layout of your children should be done in MeasureOverride and ArrangeOverrideYou should have a look at how to write custom Panels. There are tons of ressources on this topic out there. I personally think that this is a good and simple enough tutorial.
ActualHeight 是正确的属性,但在您阅读它时,尚未计算高度。
请点击此链接了解构建自定义布局面板的推荐方法:http://www.wpftutorial。 net/CustomLayoutPanel.html
ActualHeight is the correct property, but at the point where you're reading it, the height is not calculated yet.
Follow this link to find out the recommended way of building a custom layout panel: http://www.wpftutorial.net/CustomLayoutPanel.html