如何在WPF中使TextBlock可滚动

时间:2012-05-25 08:12:53

标签: c# wpf rss

我想让我的文本块区域可滚动,因为要加载很多文本。

我会把代码放在一边,因为它不是太大,所以你可以测试它。

<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 个答案:

答案 0 :(得分:6)

只需从Width中的Height移除TextBlockScrollviewer即可。顺便说一下:不需要ScrollViewer.CanContentScroll="True"

答案 1 :(得分:1)

创建可滚动文本框

在Microsoft提出使TextBlock控件可滚动的解决方案之前,以下解决方案可以正常运行。 ``` 创建一个定义单个字符串的clase;例如(在solutions文件夹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”)中定义可滚动文本的可视区域。将此区域的可视性设置为折叠,以禁止在按钮单击事件发生之前显示测试。此网格行将包含另一个Grid,其中两行定义可滚动文本控件的Xaml和Close按钮。第一个网格行将包含ScrollableView中的ListView,在我的情况下将包含在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”。

答案 2 :(得分:0)

将这些属性添加到ScrollViewer标记。允许滚动TextBlock的内容。

CanContentScroll = “真”

答案 3 :(得分: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>