问题
I have a problem with the TextBox
control.
Be aware of the ScrollViewer
as this makes the difference.
Here is my xaml:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ScrollViewer HorizontalScrollMode="Auto" HorizontalScrollBarVisibility="Auto">
<TextBox HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Margin="20"
Text = "A short text">
</TextBox>
</ScrollViewer>
</Grid>
It results in this:
It looks like expected and it expends/shrinks nicely if the window is resized. So far so good, but what happens if the text is a bit longer?
This happens:
The TextBox
now grows to fit the text inside which is
a) because there is a ScrollView
that allows horizontal scrolling and
b) results in a really ugly UI (as the right margin isn't visible, but a scrollbar is, etc..)
Does anybody know how I could achieve the look from the first screenshot even with the longer text (while keeping the ScrollViewer)?
I thought about setting a maximum width for the TextBox
but it prevented the TextBox
from growing with the window which isn't acceptable.
回答1:
I think you may confused the Width
or ActualWidth
of ScrollViewer
with its ScrollableWidth
, if you don't limit the width of TextBox
, the ScrollableWidth
will grow up with the width of TextBox
. Limit the width of the TextBox
won't solve your problem.
...the right margin isn't visible, but a scrollbar is..
I guess what you need is something like this:
xaml code:
<ScrollViewer Margin="20" BorderBrush="Blue" BorderThickness="2"
HorizontalScrollMode="Auto" HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Hidden" VerticalScrollMode="Disabled" Height="45">
<TextBox x:Name="tb" HorizontalAlignment="Stretch" VerticalAlignment="Center"
BorderThickness="0"/>
</ScrollViewer>
You can customize the ScrollViewer
to make it behavior like a TextBox
, for example when got focus, the Border
will be shown or something others.
回答2:
Change the MaxWidth
property of the TextBox
as you resize the window would solve your problem. Although, I don't think it's a clean way to do that.
int margin = 40; // Set your margin
public MainPage()
{
this.InitializeComponent();
InputTextBox.MaxWidth = Window.Current.Bounds.Width - margin;
Window.Current.SizeChanged += Current_SizeChanged;
}
private void Current_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
{
var size = e.Size;
InputTextBox.MaxWidth = size.Width - margin;
}
回答3:
Try setting the Padding property on your scrollviewer instead of Margin, try this
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">">
<ScrollViewer HorizontalScrollBarVisibility="Auto" Padding="20,0">
<TextBox HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Margin="20"
Text = "A short text">
</TextBox>
</ScrollViewer>
</Grid>
来源:https://stackoverflow.com/questions/38760810/textbox-sizing-inside-scrollview-with-horizontal-scroll