如何在WPF中使TextBlock可滚动

7
我希望让文本区域可以滚动,因为需要加载大量文字。
我会将所有代码都放出来,因为它并不太大,所以您可以进行测试。
<UserControl x:Class="Fleet_management.Info"
             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"
             mc:Ignorable="d" Height="492" Width="578">
    <UserControl.Background>
        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="#FFE2E2E2" Offset="0" />
            <GradientStop Color="White" Offset="1" />
        </LinearGradientBrush>
    </UserControl.Background>

    <UserControl.Resources>
        <XmlDataProvider x:Key="rssData" XPath="//item" Source="*******" />
    </UserControl.Resources>

    <Grid Margin="3" Height="598" Width="565">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="252*" />
            <ColumnDefinition Width="90*" />
            <ColumnDefinition Width="223*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="177*" />
            <RowDefinition Height="55*" />
            <RowDefinition Height="122*" />
            <RowDefinition Height="177*" />
        </Grid.RowDefinitions>

        <ListBox x:Name="lstItems" Margin="3,0" ItemsSource="{Binding Source={StaticResource rssData}}"
                 SelectedIndex="0" VerticalAlignment="Stretch" FontStretch="Normal" FontSize="14" FontFamily="Lucida Sans Unicode" Grid.ColumnSpan="3">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Width="20" Margin="3" Source="{Binding XPath=enclosure/@url}" />
                        <TextBlock Margin="3" VerticalAlignment="Center" Text="{Binding XPath=title}" FontWeight="Bold" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

        <StackPanel Grid.Row="1" Orientation="Vertical" DataContext="{Binding ElementName=lstItems, Path=SelectedItem}" Margin="0,0,0,5" Grid.ColumnSpan="3">
            <TextBlock Margin="3" FontSize="13" FontWeight="Bold" Text="{Binding XPath=title, Path=InnerText}" />
            <TextBlock Margin="3" Opacity="0.72" Text="{Binding XPath=pubDate}" />
        </StackPanel>
        <ScrollViewer Grid.Row="2" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto" DataContext="{Binding ElementName=lstItems, Path=SelectedItem}" Margin="0,0,3,115" Grid.RowSpan="2" Grid.ColumnSpan="3">
            <TextBlock ScrollViewer.CanContentScroll="True" Margin="3"
                       FontStyle="Italic" Text="{Binding XPath=description, Path=InnerText}" TextWrapping="Wrap" TextAlignment="Justify" Width="528" AllowDrop="False"
                       Foreground="#FF0000E7" FontFamily="Lucida Sans Unicode" Height="215" FontSize="14" Padding="0,0,5,0" />
        </ScrollViewer>

    </Grid>
</UserControl>

以下部分存在问题:

<ScrollViewer Grid.Row="2" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto" DataContext="{Binding ElementName=lstItems, Path=SelectedItem}" Margin="0,0,3,115" Grid.RowSpan="2" Grid.ColumnSpan="3">
            <TextBlock ScrollViewer.CanContentScroll="True" Margin="3"
                       FontStyle="Italic" Text="{Binding XPath=description, Path=InnerText}" TextWrapping="Wrap" TextAlignment="Justify" Width="528" AllowDrop="False"
                       Foreground="#FF0000E7" FontFamily="Lucida Sans Unicode" Height="215" FontSize="14" Padding="0,0,5,0" />
        </ScrollViewer>

代码正在加载文本,但没有全部加载出来,应该出现滚动条

4个回答

11

只需从您的Scrollviewer中删除TextBlockWidthHeight,就可以使其正常工作。顺便说一下:没有必要使用ScrollViewer.CanContentScroll="True"


哇,我真的不敢相信这是个问题。给你点赞,伙计! - user123_456

1
创建可滚动文本框
在微软提出使TextBlock控件可滚动的解决方案之前,以下解决方案能够完美地实现。
创建一个定义单个字符串的类;例如(在解决方案文件夹Concrete中创建的类):
namespace jScheduleVI.Concrete
{
    public class MyString
    {
        public string MyParagraph { get; set; }
    }
}

在您希望显示可滚动文本的页面的代码后台中,声明一个由上面创建的单个字符串类项组成的ObservableCollection:
public ObservableCollection<MyString> textList = new ObservableCollection<MyString>();

创建一个或多个按钮以激活在页面的Xaml中显示可滚动文本。例如,关于按钮和隐私政策按钮(我将这些按钮放置在Grid.Row =“0”的网格中):
<RelativePanel>            
            <Button Name="InformationButton"
                    ToolTipService.ToolTip="About"
                    RelativePanel.AlignRightWithPanel="True"
                    Margin="5"
                    Background="White"
                    Click="InformationButton_Click"
                    Width="50" Height="30"
                    HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch">
                <Image Source="Assets/InfoIcon.jpg" 
                           Stretch="UniformToFill"/>
            </Button>
            <Button x:Name="PrivacyPolicy"
                    RelativePanel.LeftOf="InformationButton"
                        ToolTipService.ToolTip="Privacy Policy"
                    Margin="0,5,0,5"
                    Background="White"
                    Click="PrivacyPolicy_Click"
                    Width="40" Height="30"
                    HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch">
                <Image Source="Assets/Icons/Privacy.png" 
                           Stretch="UniformToFill"/>
            </Button>
        </RelativePanel>

在下一个网格行(Grid.Row =“1”)中定义可滚动文本的可视区域。将此区域的可见性设置为折叠,以禁止在按钮单击事件发生之前显示测试内容。该网格行将包含另一个网格,其中有两行定义了可滚动文本控件和关闭按钮的Xaml。第一行网格将包含一个ListView,位于ScrollableView内,在我的情况下还在Border内。第二行包含关闭按钮。

<Grid Grid.Row="1"
                    x:Name="ScrollableText"                                       
                    Visibility="Collapsed"
                    Margin="10">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <Border BorderThickness="2" 
                    BorderBrush="Gray">
                <ScrollViewer ScrollViewer.VerticalScrollMode="Auto">
                    <ListView ItemsSource="{x:Bind textList}"
                              HorizontalAlignment="Stretch"
                              HorizontalContentAlignment="Stretch" 
                              ItemTemplate="{StaticResource TextBlockDataTemplate}"
                              Height="500">
                        <ListView.ItemContainerStyle>
                            <Style TargetType="ListViewItem">
                                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                            </Style>
                        </ListView.ItemContainerStyle>
                    </ListView>
                </ScrollViewer>
            </Border>

            <Button Grid.Row="1" 
                    Name="CloseButton" 
                    Content="Close" 
                    Click="CloseButton_Click" 
                    Margin="10"/>
        </Grid>

ListView的ItemTemplate定义在显示可滚动文本的页面上的页面资源中(对于更复杂的可滚动文本,模板可以在UserControl中定义),例如:
<DataTemplate x:Key="TextBlockDataTemplate" x:DataType="data:MyString">
            <TextBlock HorizontalAlignment="Left" 
                           TextWrapping="Wrap"
                           FontSize="16"
                           FontFamily="Global Sans Serif"
                           Margin="10" 
                           Height="Auto"
                       Text="{x:Bind MyParagraph}"/>
        </DataTemplate>

然后,在每个按钮的Click事件中,放置可滚动文本。该文本将由单个字符串类(在我的示例中为MyString)类型的段落列表组成,这些段落被添加到为ListView定义的ObservableCollection中。为了使集合可以用于多个可滚动文本视图,首先清除集合,然后再添加文本。一旦集合完成,Grid.Row =“1”将变为可见。

private void InformationButton_Click(object sender, RoutedEventArgs e)
        {
            textList.Clear();
            MyString line = new MyString();
            line.MyParagraph = "jMajorsIV provides golf score data management of 9 or 18 hole competition golf in a format that mimics play of the PGA tour major tournaments, namely The Masters, The US Open, the PGA, and The British Open. Each major tourney consists of four rounds and scoring is based on net score using a progressive handicap calculated weekly. Player standings at the end of each major are awarded Cup Points according to their finish. At the end of the four major tourneys, the players can decide on the cup points cut-off for participation in the Cup Championship.";
            textList.Add(line);
            MyString line1 = new MyString();
            line1.MyParagraph = "Competition can include at little as two players, personal groups, as well as organized leagues. Scoring can be entered at any time allowing play to conform to available play times and dates. Leader boards will show the latest round scored and the net score for that round while players not yet completing rounds will show dash marks for a current score. Over or under par total scores for each player for rounds completed will determine standings for the tourney.";
            textList.Add(line1);
            MyString line2 = new MyString();
            line2.MyParagraph = "Users are presented with a setup page to allow course data settings to be entered for the type of players competing(seniors, women, mixed, men's) and consists of tee slope and ratings, tee par per hole, tee hole handicap per hole, along with the course name or group name. The setup page provides for initial player entry but does not require all players to be entered; players an join as the competition ensues throughout the season. Play format is also selected for the competition and allows for settings the handicap percentage to be used for net scoring.";
            textList.Add(line2);
            MyString line3 = new MyString();
            line3.MyParagraph = "Scoring is entered by individual players or by a designee on consists of the gross score for each hole. Equitable score control is used based on the players handicap index to adjust gross score entries for net score determination. Handicap dots and over - under score are maintained as each hole score is entered. Leader score boards will automatically update as a score is entered. Player statistics are tabulated and displayed for each tournament round and for each hole on the course.";
            textList.Add(line3);
            MyString line4 = new MyString();
            line4.MyParagraph = " Comments and suggestions are welcome and can be sent to: jbhSolutionsLM@gmail.com   Product of jbhSolutions - Lake Monticello, VA";
            textList.Add(line4);
            ScrollableText.Visibility = Visibility.Visible;
        }

点击关闭按钮会折叠在页面上显示的可滚动视图区域:

private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            ScrollableText.Visibility = Visibility.Collapsed;
        }

访问网络和Microsoft应用商店上的“jbhSolutions”以查看此控件的示例。

0
将以下属性添加到 ScrollViewer 标记中,可以滚动 TextBlock 的内容。

CanContentScroll="True"


1
我已经放置了它,但它没有起作用。你能否在你的项目中尝试这个例子? - user123_456

0

这是您修改过的XAML代码,并且它正常工作。

我根据我的数据更改了绑定。您需要根据您的数据成员进行更改。

<Grid Margin="3">

        <Grid.RowDefinitions>
            <RowDefinition Height="177*" />
            <RowDefinition Height="100*" />
            <RowDefinition Height="122*" />
            <RowDefinition Height="177*" />
        </Grid.RowDefinitions>

        <ListBox x:Name="lstItems"
                 Grid.ColumnSpan="3"
                 Margin="3,0"
                 VerticalAlignment="Stretch"
                 FontFamily="Lucida Sans Unicode"
                 FontSize="14"
                 FontStretch="Normal"
                 SelectedIndex="0">
            <ListBox.Background>
                <ImageBrush />
            </ListBox.Background>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Width="100"
                                   Margin="3"
                                   Text="{Binding Name}" />
                        <TextBlock Margin="3"
                                   VerticalAlignment="Center"
                                   FontWeight="Bold"
                                   Text="{Binding InceptionDate}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

        <StackPanel Grid.Row="1"
                    Margin="5"
                    DataContext="{Binding ElementName=lstItems,
                                          Path=SelectedItem}"
                    Orientation="Vertical">
            <TextBlock Margin="3"
                       FontSize="13"
                       FontWeight="Bold"
                       Foreground="Red"
                       MaxHeight="50"
                       Text="{Binding FundSummary}"
                       TextWrapping="Wrap" />
            <TextBlock Margin="3"
                       Foreground="Blue"
                       Opacity="0.72"
                       ScrollViewer.CanContentScroll="True"
                       ScrollViewer.VerticalScrollBarVisibility="Auto"
                       Text="{Binding ManagerBio}"
                       TextWrapping="WrapWithOverflow" />
        </StackPanel>
        <ScrollViewer Grid.Row="2"
                      Grid.RowSpan="2"
                      Grid.ColumnSpan="3"
                      Margin="10"
                      DataContext="{Binding ElementName=lstItems,
                                            Path=SelectedItem}"
                      HorizontalScrollBarVisibility="Disabled"
                      VerticalScrollBarVisibility="Auto">

            <TextBlock Height="Auto"
                       Margin="3"
                       AllowDrop="False"
                       Background="Silver"
                       FontFamily="Lucida Sans Unicode"
                       FontSize="14"
                       FontStyle="Italic"
                       Foreground="YellowGreen"
                       Padding="0,0,5,0"
                       ScrollViewer.CanContentScroll="True"
                       Text="{Binding ManagerBio}"
                       TextAlignment="Justify"
                       TextWrapping="Wrap" />

        </ScrollViewer>
    </Grid>

这对我不起作用...你能试试我的代码或将我的绑定放在你的代码里吗?因为我无法加载任何东西。 - user123_456

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接