简体   繁体   English

WPF,随着TextBox调整窗口大小

[英]WPF, Window resizing as TextBox resizes

So I posted this question but the suggested answers do not seem to work. 所以我发布了这个问题,但是建议的答案似乎不起作用。 So once again, re-posting it, much simpler version of the XAML. 因此,再次发布它,它是XAML的简单得多的版本。 We usually expect the TextBox to resize as the Window resize. 通常,我们希望TextBox会随着Window的大小而改变。 I want the "other-way-around" behavior. 我想要“其他方式”的行为。 TextBox that takes the whole Window area. 占据整个Window区域的TextBox。 The TextBox grows/shrinks in size, the Window follows. TextBox的大小会增加/缩小,接着是Window。 Please suggest on ways doing it. 请提出建议。

<Window>
    <Grid HorizontalAlignment="Stretch">
        <TextBox Width="Auto">            
        </TextBox>
    </Grid>
 </Window>
<Window x:Class="MiscSamples.SizeToContent"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SizeToContent" SizeToContent="WidthAndHeight" ResizeMode="NoResize">
    <Grid HorizontalAlignment="Stretch">
        <TextBox Width="Auto" AcceptsReturn="True">
        </TextBox>
    </Grid>
</Window>

Notice that you have to include ResizeMode="NoResize" , because if the user resizes the window manually, the behavior is lost. 请注意,您必须包括ResizeMode="NoResize" ,因为如果用户手动调整窗口大小,则该行为将丢失。

You could give the textbox a name and then bind the window width to the size of the textbox as such: 您可以为文本框命名,然后将窗口宽度绑定到文本框的大小,如下所示:

<Window Width="{Binding ElementName=txtbox, Path=ActualWidth}">
   <Grid HorizontalAlignment="Stretch">
      <TextBox x:Name="txtbox" Width="Auto">            
      </TextBox>
   </Grid>
</Window>

I've not included any code for sizing the textbox (I assume you're going to do that programmatically or so) but with this XAML the window should size to the textbox width. 我没有包含任何用于调整文本框大小的代码(我假设您将以编程方式进行此操作),但是使用此XAML,窗口的大小应与文本框的宽度相同。

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

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