wrapping content in a StackPanel wpf

2019-06-15 01:11发布

问题:

is it possible to wrap content in a StackPanel?

I know that we can make use of a WrapPanel instead. But for code modifying reasons, I must make use of a StackPanel.

So, is there a way to make the items in a StackPanel wrap after say 5 items... Thanks!

回答1:

Create nested StackPanels which contain the required number of items.

In the example below, you have two rows, respectively occupied by the <StackPanel Orientation="Horizontal"> elements, which in turn each contain five items that will be displayed horizontally next to each other.

<StackPanel Orientation="Vertical">
    <StackPanel Orientation="Horizontal">
        <Item1 />
        <Item2 />
        <Item3 />
        <Item4 />
        <Item5 />
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <Item1 />
        <Item2 />
        <Item3 />
        <Item4 />
        <Item5 />
    </StackPanel>
</StackPanel>


回答2:

For me, a simple WrapPanel works just fine:

<WrapPanel Orientation="Horizontal" Width="500" />

Not inside a StackPanel or any other container. And setting Width to a constant value can be superior im some cases, because binding it to ActualWidth can prevent down-sizing (e.g. when parent control is down-sized, WrapPanel is not)



回答3:

<StackPanel>
        <StackPanel.Style>
            <Style TargetType="{x:Type StackPanel}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type StackPanel}">
                            <WrapPanel/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </StackPanel.Style>
    </StackPanel>


回答4:

Depending on your scenario you could use a UniformGrid. A few example can also be found here.

You can define it to wrap after 5 Items like this.

<UniformGrid Columns="5">
 <Button />
 <Button />
 <Button />
</UniformGrid>

Each Item will, however get the exact same width, so not sure if this will work for you.



回答5:

I don't think you can do it without a wrap panel. Maybe you can try putting a wrapPanel inside the stack panel - set its width to to the Actual width of the stack panel. You can bind it like Width="{Binding ActualWidth, ElementName=StackPanel1}"

But this will be just a hack - i think wrap panel is the best suited for your needs.



回答6:

I put a stackpanel over the button. It won't affect button background. Then in the VB code I used Chr(12), to indicate a line feed:

Button1.Content = "first line" + Chr(12) + "second line"

You can add more lines using Chr(12).