我一直遇到一个问题,我希望应用程序中的文本框能够随窗口动态调整大小,但在用户输入文本时不会展开。
然而,在搜索之后,似乎没有一个通用的解决方案来修复应用程序中的所有文本框,而不是为文本框的MaxWidth
和MaxHeight
属性添加XAML绑定。
所以我创建了以下控件,以便在Measure()
调用后自动锁定文本框尺寸:
<TextBox x:Class="GUI.Views.Controls.FixedTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
</TextBox>
public partial class FixedTextBox : TextBox
{
public FixedTextBox()
{
InitializeComponent();
}
protected override Size MeasureOverride(Size constraint)
{
UnboundDimensions();
var measured = base.MeasureOverride(constraint);
BoundDimensions();
return measured;
}
private void UnboundDimensions()
{
MaxWidth = Double.PositiveInfinity;
MaxHeight = Double.PositiveInfinity;
}
private void BoundDimensions()
{
MaxWidth = ActualWidth > 0 ? ActualWidth : Double.PositiveInfinity;
MaxHeight = ActualHeight > 0 ? ActualHeight : Double.PositiveInfinity;
}
}
这个解决方案运行正常,但我想知道在我查看XAML代码并将文本框更改为自定义控件之前是否有更好的方法....?
编辑(问题示例):https://dl.dropboxusercontent.com/u/28956841/TextBoxTrouble.zip
<Window x:Class="TextBoxTrouble.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="150" Width="500">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
<Grid Grid.IsSharedSizeScope="True">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="Labels"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="5"></ColumnDefinition>
<ColumnDefinition SharedSizeGroup="Labels"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Label Grid.Column="0"
Grid.Row="0"
VerticalContentAlignment="Center">Label 1</Label>
<TextBox Grid.Column="1"
Grid.Row="0"
Margin="10">Some text</TextBox>
<Label Grid.Column="3"
Grid.Row="0"
VerticalContentAlignment="Center">Label 2</Label>
<TextBox Grid.Column="4"
Grid.Row="0"
Grid.RowSpan="2"
Margin="10"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
AcceptsReturn="True"
TextWrapping="Wrap">Some multiline text</TextBox>
</Grid>
</ScrollViewer>
</Window>
答案 0 :(得分:1)
您发布的代码中的问题(我发现找到您的问题所需的全部内容是MainWindow.xaml的内容)是您需要为最外面的HorizontalScrollBarVisibility="Disabled"
设置ScrollViewer
<Window x:Class="TextBoxTrouble.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="150" Width="500">
<ScrollViewer HorizontalScrollBarVisibility="Auto" <!-- THIS LINE -->
VerticalScrollBarVisibility="Auto">