Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make TextBlock scrollable inWPF

Tags:

c#

rss

wpf

I want to have my textblock area scrollable as there is a lot text to load.

I will put al of the code as it is not too big so you can test it.

<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>

This is the part that is not working correctly:

<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>

Code is loading text but not all of it, there should be scroll

like image 433
user123_456 Avatar asked May 25 '12 08:05

user123_456


2 Answers

Just remove Width and Height from your TextBlock in Scrollviewer and it should work. By the way: there is no need for ScrollViewer.CanContentScroll="True".

like image 65
LPL Avatar answered Oct 17 '22 23:10

LPL


Creating A Scrollable Text Box

Until Microsoft comes up with a solution to make the TextBlock control scrollable, the following solution works flawlessly. ``` Create a clase that defines a single string; for example (class created within the solutions folder Concrete):

namespace jScheduleVI.Concrete
{
    public class MyString
    {
        public string MyParagraph { get; set; }
    }
}

Within the code behind for the page on which you wish to display the scrollable text, declare an ObservableCollection of the single string class items created above:

public ObservableCollection<MyString> textList = new ObservableCollection<MyString>();

Create one or more buttons to activate display of your scrollable text within the Xaml for the page on which it will be displayed. For example an About button and a Privacy Policy button (I placed these buttons within a Grid in 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>

Within the next grid row (Grid.Row=”1”) define the viewable area for the scrollable text. Set the vidibility for this area to collapsed to prohibit display of the test until the button click events occur. This grid row will house another Grid with two rows defining the Xaml for the scrollable text control and a Close button. The first grid row will contain a ListView within a ScrollableView and in my case within a Border. The second row contains the Close button.

<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>

The ItemTemplate for the ListView is defined within the Page Resource on the page displaying the scrollable text (for more complicated scrollable text, the template can be defined within a UserControl) for example:

<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>

Then within the Click events for each button, place the scrollable text. The text will consist of a list of paragraphs of type single string class (in my example MyString) which are added to the ObservableCollection defined for the ListView. So that the collection can be used for multiple views of scrollable text, the collection is cleared first before text is added. Once the collection is complete, the Grid.Row=”1” is made visible.

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: [email protected]   Product of jbhSolutions - Lake Monticello, VA";
            textList.Add(line4);
            ScrollableText.Visibility = Visibility.Visible;
        }

The Close button click event collapses the scrollable view area displayed on the page:

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

For examples of this control in action visit “jbhSolutions” on the web and Microsoft app store.

like image 43
jbhSolutions Avatar answered Oct 17 '22 22:10

jbhSolutions