开发者

C# WPF - ScrollViewer + TextBlock troubles

I have a TextBlock within a ScrollViewer that aligns with stretch to its window. I need the TextBlock to behave as the following:

  • Resizes with window, no scrollbars
  • When resized below a certain width the TextBlock needs to keep a MinWidth and scrollbars should appear
  • TextWrapping or TextTrimming should work appropriately

How can I get this functionality?

I have tried several ways, involving bindings to ActualWidth & ActualHeight, but can't get it to work.

This can't be that difficult, what am I missing?

Here is a code sample to put in XamlPad (no MinWidth is set yet):

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <TextBlock TextWrapping="Wrap" Text="Some really long text that should probabl开发者_运维技巧y wordwrap when you resize the window." />
    </ScrollViewer>
</Window>


This works:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ScrollViewer HorizontalScrollBarVisibility="Auto" 
                  VerticalScrollBarVisibility="Auto"
                  Name="Scroller">
        <TextBlock HorizontalAlignment="Stretch"
                   VerticalAlignment="Stretch"
                   MinWidth="100"
                   Width="{Binding ElementName=Scroller, Path=ViewportWidth}"
                   TextWrapping="Wrap"
                   Text="Some really long text that should probably wordwrap when you resize the window." />
    </ScrollViewer>
</Window>


Without more detail, the best I can do is provide the standard way of doing this. Basically, host your element (which has a minimum size) in a scroll viewer; when the scrollviewer is resized small enough such that the element cannot wholly fit inside it, it will automatically display scroll bars. Example:

<ScrollViewer>
    <Button MinWidth="100" MinHeight="50"/>
</ScrollViewer>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜