简体   繁体   English

调整控件的宽度和高度以包装其内容

[英]Adjust width and height of a control to wrap its content

How can I do to set the Width/Height of a Windows Phone control to be just the minimum necessary to wrap its content? 如何将Windows Phone控件的Width / Height设置为包装其内容所需的最小值? In Android I would have done it the following way: 在Android中,我可以通过以下方式进行操作:

android:layout_width="wrap_content"

Thank you 谢谢

You could use a ViewBox. 您可以使用ViewBox。 This will scale the content inside to fit the space available. 这将缩放内部内容以适应可用空间。

<ViewBox>
    <Grid Width="Auto" Height="Auto"> 
    <!-- Your content goes here -->
    <Grid/>
<ViewBox/>

Controls have some properties wich you can make use of: MinWidth , MaxWidth , Width , some controls with text content have also TextWrapping and TextTrimming . 控件具有一些可以利用的属性: MinWidthMaxWidthWidth ,一些具有文本内容的控件还具有TextWrappingTextTrimming By using those you will probably achieve what you want - some examples: 通过使用这些功能,您可能会实现所需的功能-一些示例:

<StackPanel Margin="20">
    <StackPanel.Resources>
        <Style TargetType="Border">
            <Setter Property="BorderBrush" Value="Red"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="HorizontalAlignment" Value="Left"/>
            <Setter Property="Margin" Value="0,0,0,10"/>
        </Style>
        <Style TargetType="TextBlock">
            <Setter Property="HorizontalAlignment" Value="Left"/>
            <Setter Property="FontSize" Value="20"/>
            <Setter Property="Text" Value="Simple long description"/>
        </Style>
    </StackPanel.Resources>
    <Border> <!-- Implicit width -->
        <TextBlock Width="150"/>
    </Border>
    <Border> <!-- Implicit width with text wrapping -->
        <TextBlock Width="150" TextWrapping="Wrap"/>
    </Border>
    <Border> <!-- Auto width -->
        <TextBlock Width="Auto"/>
    </Border>
    <Border> <!-- Auto width but with limit -->
        <TextBlock Width="Auto" MaxWidth="180"/>
    </Border>
    <Border> <!-- Short text with min width -->
        <TextBlock Width="Auto" MinWidth="100" Text="Min"/>
    </Border>
    <Button> <!-- Button with wrapped text -->
        <TextBlock Width="120" TextWrapping="Wrap"/>
    </Button>
</StackPanel>

The result: 结果:

在此处输入图片说明

In some cases you will probably also what to use HorizontalAlignment = Stretch which will set control's width to available space. 在某些情况下,您可能还会使用HorizontalAlignment = Stretch ,它将控件的宽度设置为可用空间。

You can use width="Auto" and height="Auto" attribute of the respective controls. 您可以使用相应控件的width="Auto"height="Auto"属性。

For example 例如

<StackPanel>
    <TextBlock x:Name="textBlock" Width="Auto" Text="Sample Text" />
</StackPanel>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM