WPF - setting HorizontalAlignment= Stretch to Textbox in StackPanel

眉间皱痕 提交于 2019-12-03 23:58:39
Kent Boogaart

Yes, it's by design. The StackPanel will allocate the space the TextBox asks for. If you haven't set a width on the TextBox, it will require only enough width to fit its text.

Kent's answer seems right.
To still force override the StackPanel behavior, I think you'd need to dynamically compute-set the Width property of the contained elements OR some funky override of MeasureOverride. I'd rather use another layout manager/panel. Some things I noted..

  • The default value for HorizontalAlignment and VerticalAlignment properties of child elements is Stretch (if you don't specify one explicitly).
  • The StackPanel will stretch elements based on its Orientation property value. So

    • Orientation=Horizontal means all elements will be vertically stretched to max. Elements flow horizontally.
    • Orientation=Vertical means all elements will be horiz stretched to max. Elements flow vertically.
  • Unless explicitly specified, Width and Height of child elements are NaN. If you specify an explicit value, StackPanel will honor them over the Horiz and Vert Alignment settings.
  • The StackPanel itself has HorizontalAlignment and VerticalAlignment that adds a further layout twist. You can experiment with this example.

StackPanel

The default value is stretch for both HorizontalAlignment and VerticalAlignment of content that is contained in a StackPanel.

HorizontalAlignment

When Height and Width properties are explicitly set on an element, these measurements take higher precedent during layout and will cancel the typical effects of setting HorizontalAlignment to Stretch.

I needed items to be sized evenly, but stacked vertically.

I used a UniformGrid, and set the Columns property to 1. (tested with a TextBox, and it stretches like you want)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!