开发者

How to stop a panel's children from exceeding the bounds if the panel's MaxWidth is set?

I have observed this problem in Grids and StackPanels, it might apply to other panels too, consider the following Xamls:

<Grid MaxWidth="200">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Label>Title:</Label>
    <TextBox Grid.Column="1" Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

and

<StackPanel MaxWidth="200">
    <Label>Title:</Label>
    <TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>

(Edit: I have several such variable blocks that is why i don't set the MaxWidth of the TextBox itself)

Of course what i want is that upon text input the TextBox does not grow any bigger if the parent's MaxWidth is reached, this however does not happen, the panel resizes till it reaches the MaxWidth and the TextBox shoots outside of bounds.

If the second grid-column has no Width defined (one star by default) the TextBox will not grow since it just takes all the available space so the text scrolls like i want it too but this panel is an item in a ToolBar and if the ToolBar is in a horizontal ToolBarTray this setting causes an instant overflow.

Any ideas on how to get the TextBox to not go out of bounds?

Edit: The answers (probably) work in normal scenarios but the ToolBar somehow screws my layout over, for one thing my controls always get pushed into the ToolBar overflow area for whatever reason and contents that before stretched inside a Grid-cell no longer do so. Since my original question was how to prevent this internal overflow (and no开发者_运维知识库t how to cope with the ToolBar's peculiarities) i'll just leave it at that.


Change the second ColumnDefinition Width to *, set the textbox HorizontalAlignment to stretch and TextWrapping to Wrap to get the effect you want (see XAML below)

<Grid x:Name="myGrid" MinWidth="200" MaxWidth="200">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Label>Title:</Label>
    <TextBox Margin="5" TextWrapping="Wrap" Grid.Column="1" Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}"
             HorizontalAlignment="Stretch"/>
</Grid>

Edit: You can create a Style to be applied to text boxes so that you don't have to keep setting the same properties again for other text boxes.


Another possibility:

    <DockPanel MaxWidth="200">
        <Label DockPanel.Dock="Left" VerticalAlignment="Center">Title:</Label>
        <TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" 
                 TextWrapping="Wrap" VerticalAlignment="Center"/>
    </DockPanel>


I don't sure if it's not contradict to your application requirements but did you try to set the the MaxLength of the TextBox ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜