分页效能,从长商议Silverlight

[索引页]
[源码下载]

前台xaml文件

多加商量Silverlight(42) – 四.0控件之Viewbox, RichTextBox

<Window x:Class=”Supplier.UserI”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=”clr-namespace:Supplier”
Title=”查看用户” Height=”500″ Width=”440″ Loaded=”Window_Loaded”
WindowStartupLocation=”CenterScreen”>
<Grid >
<Grid.Resources>
<local:TypeConvert x:Key=”typeConvert”/>
<DataTemplate x:Key=”oprate” DataType=”User”>
<StackPanel Orientation=”Horizontal”>
<Button Tag=”{Binding}” Click=”updateUser” Content=”修改”
Background=”Gray” Width=”40″ Foreground=”White”/>
<Button Tag=”{Binding}” Click=”deleteUser” Content=”删除”
Background=”red” Width=”40″ Foreground=”White”/>
</StackPanel>
</DataTemplate>
<!–<DataTemplate x:Key=”permis” DataType=”User” >
<ComboBox x:Name=”permission” SelectedIndex=”{Binding Type}” >
<TextBlock Text=”全部操作” />
<TextBlock Text=”查看” Margin=”10,0,0,0″ />
</ComboBox>
</DataTemplate>–>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height=”50″/>
<RowDefinition Height=”*”/>
<RowDefinition Height=”100″/>
</Grid.RowDefinitions>
<TextBlock Grid.Row=”0″ Text=”用户处理” VerticalAlignment=”Center”
HorizontalAlignment=”Center” FontSize=”1八” FontStyle=”Normal”
Foreground=”Blue”/>
<Button Click=”addUser” Grid.Row=”0″ Content=”添加”
HorizontalAlignment=”Right” VerticalAlignment=”Center” Margin=”0,0,10,0″
Background=”SkyBlue” Width=”50″ Foreground=”White”/>
<!–Beige–>
<ListView x:Name=”grid” Grid.Row=”1″ Margin=”10,0,10,10″>
<ListView.View>
<GridView>
<GridViewColumn Header=”序号” Width=”60″
DisplayMemberBinding=”{Binding Number}”/>
<GridViewColumn Header=”用户名” Width=”80″
DisplayMemberBinding=”{Binding UserName}”/>
<GridViewColumn Header=”权限” Width=”110″
DisplayMemberBinding=”{Binding Type,Converter={StaticResource
typeConvert}}”/>
<GridViewColumn Header=”操作” Width=”120″
CellTemplate=”{StaticResource oprate}”/>
</GridView>
</ListView.View>
</ListView>
<Grid Grid.Row=”2″>
<Button Content=”上一页” Height=”23″ HorizontalAlignment=”Left”
Margin=”37,0,0,0″ Name=”button7″ VerticalAlignment=”Top” Width=”65″
Click=”PreviousPage” />
<Button Content=”下一页” Height=”23″ HorizontalAlignment=”Left”
Margin=”108,0,0,0″ Name=”button8″ VerticalAlignment=”Top” Width=”59″
Click=”NextPage” />
<Label Content=”转到” Height=”28″ HorizontalAlignment=”Left”
Margin=”173,0,0,0″ Name=”label6″ VerticalAlignment=”Top” />
<TextBox KeyDown=”textBox1_KeyDown” Height=”23″
HorizontalAlignment=”Left” Margin=”212,0,0,0″ Name=”textBox1″
VerticalAlignment=”Top” Width=”53″ />
<Button Content=”GO” Height=”23″ HorizontalAlignment=”Left”
Margin=”298,0,0,0″ Name=”button9″ VerticalAlignment=”Top” Width=”96″
Click=”JumpPage” />
<Label Content=”页” Height=”28″ HorizontalAlignment=”Left”
Margin=”269,0,0,0″ Name=”label7″ VerticalAlignment=”Top” />
<Label Height=”28″ HorizontalAlignment=”Left” Margin=”120,40,0,0″
Name=”label8″ VerticalAlignment=”Top” Content=”【第” />
<Label Content=”1″ Height=”28″ HorizontalAlignment=”Left”
Margin=”157,40,0,0″ Name=”label1″ VerticalAlignment=”Top” />
<Label Content=”页】” Height=”28″ HorizontalAlignment=”Left”
Margin=”176,40,0,0″ Name=”label10″ VerticalAlignment=”Top” />
<Label Content=”【共” Height=”28″ HorizontalAlignment=”Left”
Margin=”242,40,0,0″ Name=”label11″ VerticalAlignment=”Top” />
<Label Content=”1″ Height=”28″ HorizontalAlignment=”Left”
Margin=”280,40,0,0″ Name=”label2″ VerticalAlignment=”Top” />
<Label Content=”页】” Height=”28″ HorizontalAlignment=”Left”
Margin=”298,40,0,0″ Name=”label13″ VerticalAlignment=”Top” />
</Grid>

作者:webabcd

</Grid>
</Window>

介绍
Silverlight 四.0 控件一览:

 

  • Viewbox – 三个器皿控件,其内只好有一个子成分。Viewbox
    能够操纵其内的子成分怎么着拉伸、缩放、对齐
  • RichTextBox – 编辑器。用于显示或编辑文本、超链、图片、UI成分等 

后台

在线DEMO
http://www.cnblogs.com/webabcd/archive/2010/08/09/1795417.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;

示例
 1、Viewbox 的 Demo
ViewboxDemo.xaml

namespace Supplier
{
/// <summary>
/// 艾德it.xaml 的互相逻辑
/// </summary>
public partial class UserI : Window
{
public int pageSize = Global.PageSize; //每页记录数
private int recordsum = 0; //表中著录总量
private int PageSum = 0; //总页数
private int CurrentPage = 1; //当前页
private List<User> CurrentList;

图片 1图片 2代码

public UserI()
{
InitializeComponent();
this.Topmost = true;//顶置窗口
}

<navigation:Page x:Class=”Silverlight40.Control.ViewboxDemo” 
           xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” 
           xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” 
           xmlns:d=”http://schemas.microsoft.com/expression/blend/2008
           xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006
           xmlns:navigation=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation”
           Title=”ViewboxDemo Page”>
    <Grid x:Name=”LayoutRoot” Background=”White”>
        <StackPanel Background=”AntiqueWhite” HorizontalAlignment=”Left”>

private void Window_Loaded(object sender, RoutedEventArgs e)
{
//pageIndex 当前页的序号
recordsum = UserManager.getCount();

            <!– 用于演示 Viewbox.Stretch 属性 –>
            <StackPanel Margin=”5″ Width=”200″>
                <TextBlock Text=”Stretch” />
                <Button Name=”btn1″ Click=”stretchNone” Content=”None” />
                <Button Name=”btn2″ Click=”stretchFill” Content=”Fill” />
                <Button Name=”btn3″ Click=”stretchUniform” Content=”Uniform” />
                <Button Name=”btn4″ Click=”stretchUniformToFill” Content=”UniformToFill” />
            </StackPanel>

//决断总页数
if (recordsum % pageSize == 0)
PageSum = recordsum / pageSize;
else
PageSum = recordsum / pageSize + 1;

            <!– 用于演示 Viewbox.StretchDirection 属性 –>
            <StackPanel Margin=”5″ Width=”200″>
                <TextBlock Text=”StretchDirection” />
                <Button Name=”btn5″ Click=”stretchDirectionUpOnly” Content=”UpOnly” />
                <Button Name=”btn6″ Click=”stretchDirectionDownOnly” Content=”DownOnly” />
                <Button Name=”btn7″ Click=”stretchDirectionBoth” Content=”Both” />
            </StackPanel>

DataGridBind(CurrentPage);
}
#region 用户操作
private void updateUser(object sender, RoutedEventArgs e)
{
UserEdit userEdit = new UserEdit();
Button bt = e.OriginalSource as Button;
User u = bt.Tag as User;
userEdit.user = u;
userEdit.hasType = true;
bool? result = userEdit.ShowDialog();
if (result != null && (bool)result)
{
Window_Loaded(sender, e);
DataGridBind(CurrentPage);
}
}
private void deleteUser(object sender, RoutedEventArgs e)
{
if (MessageBox.Show(“您分明要去除该用户吗?”, “系统提醒”,
MessageBoxButton.YesNo, MessageBoxImage.Warning) ==
MessageBoxResult.Yes)
{
UserEdit userEdit = new UserEdit();
Button bt = e.OriginalSource as Button;
User u = bt.Tag as User;
UserManager.delete(u.ID);
Window_Loaded(sender, e);
DataGridBind(CurrentPage);
}
}

            <!– 用于演示 Viewbox.HorizontalAlignment 属性 –>
            <StackPanel Margin=”5″ Width=”200″>
                <TextBlock Text=”HorizontalAlignment” />
                <Button Name=”btn8″ Click=”horizontalAlignmentCenter” Content=”Center” />
                <Button Name=”btn9″ Click=”horizontalAlignmentLeft” Content=”Left” />
                <Button Name=”btn10″ Click=”horizontalAlignmentRight” Content=”Right” />
                <Button Name=”btn11″ Click=”horizontalAlignmentStretch” Content=”Stretch” />
            </StackPanel>

private void addUser(object sender, RoutedEventArgs e)
{
UserAdd userAdd = new UserAdd();
userAdd.hasType = true;
bool? result = userAdd.ShowDialog();
if (result != null && (bool)result)
{
Window_Loaded(sender, e);
DataGridBind(PageSum);
}
}
#endregion
#region 分页

            <!– 用于演示 Viewbox.VerticalAlignment 属性 –>
            <StackPanel Margin=”5″ Width=”200″>
                <TextBlock Text=”VerticalAlignment” />
                <Button Name=”btn12″ Click=”verticalAlignmentCenter” Content=”Center” />
                <Button Name=”btn13″ Click=”verticalAlignmentTop” Content=”Top” />
                <Button Name=”btn14″ Click=”verticalAlignmentBottom” Content=”Bottom” />
                <Button Name=”btn15″ Click=”verticalAlignmentStretch” Content=”Stretch” />
            </StackPanel>

private void DataGridBind(int pageIndex)
{
if (pageIndex > 0)
{
CurrentList = UserManager.getList((pageIndex – 1) * pageSize,
pageSize);
this.grid.ItemsSource = CurrentList;
CurrentPage = pageIndex;
label1.Content = CurrentPage;
label2.Content = PageSum;
}
}

            <!– 用于显示当前 Viewbox 的 Stretch 值,StretchDirection 值,HorizontalAlignment 值,VerticalAlignment 值 –>
            <StackPanel Margin=”5″>
                <TextBlock Name=”lblMsg” />
            </StackPanel>

/// <summary>
/// 上一页
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void PreviousPage(object sender, RoutedEventArgs e)
{
if (CurrentPage > 1)
DataGridBind(CurrentPage – 1);
}
/// <summary>
/// 下一页
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void NextPage(object sender, RoutedEventArgs e)
{
if (CurrentPage < PageSum)
DataGridBind(CurrentPage + 1);
}
/// <summary>
/// 跳转页
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void JumpPage(object sender, RoutedEventArgs e)
{
int page = 0;
if (int.TryParse(textBox1.Text, out page))
{
if(page<=PageSum)
DataGridBind(page);
else
{
MessageBox.Show(“对不起,您输入的页面抢先这段时间最大页数”, “提醒”,
MessageBoxButton.OK, MessageBoxImage.Information);
this.textBox1.Clear();
}
}

            <!– 用于演示 Viewbox 的各类功用 –>
            <StackPanel Width=”500″ Height=”300″ Background=”Black”>
                <Viewbox Name=”viewbox” Width=”500″ Height=”300″>
                    <!– 注:Viewbox 内只好有2个子元素 –>
                    <Image Source=”/Resource/Logo.jpg” />
                </Viewbox>
            </StackPanel>
            
        </StackPanel>
    </Grid>
</navigation:Page>

}

ViewboxDemo.xaml.cs

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
JumpPage(sender, e);
}
#endregion

图片 3图片 4代码

}
}

/*
 * Viewbox – 3个器皿控件,其内只能有2个子成分。Viewbox 能够操纵其内的子成分怎么样拉伸、缩放、对齐
 */

多少操作model 层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

/// <summary>
/// 获取第skipNum到(skipNum+pageSize)内的笔录
/// </summary>
/// <param name=”skipNum”></param>
/// <param name=”pageSize”></param>
/// <returns></returns>
public static List<User> getList(int skipNum, int pageSize)
{
string sql = “select top ” + pageSize + ” Number= row_number()
over(order by id asc), * from Users where id not in ”

namespace Silverlight40.Control
{
    public partial class ViewboxDemo : Page
    {
        public ViewboxDemo()
        {
            InitializeComponent();
        }

  • “(select top ” + skipNum + ” id from Users order by id asc) order by
    id asc”;
    DataTable dataTable = DbConHelper.ExecuteDataTable(sql);
    List<User> userList = new List<User>();
    User userModel;
    if (dataTable.Rows.Count > 0)
    {
    int page = skipNum / pageSize+1;
    foreach (DataRow row in dataTable.Rows)
    {
    userModel = new User()
    {
    ID = row[“ID”].ToString().Trim(),
    Number = (int.Parse(row[“Number”].ToString().Trim()) *
    page).ToString(),
    Password = row[“Password”].ToString().Trim(),
    Type = row[“Type”].ToString().Trim(),
    UserName = row[“UserName”].ToString().Trim()

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ShowResult();
        }

};
userList.Add(userModel);
}
}
return userList;

        // 用于体现当前 Viewbox 的 Stretch 值,StretchDirection 值,HorizontalAlignment 值,VerticalAlignment 值
        private void ShowResult()
        {
            lblMsg.Text = string.Format(“Stretch: {0}, StretchDirection: {1}, HorizontalAlignment: {2}, VerticalAlignment: {3}”,
                viewbox.Stretch.ToString(),
                viewbox.StretchDirection.ToString(),
                viewbox.HorizontalAlignment.ToString(),
                viewbox.VerticalAlignment.ToString());
        }

}

        /*
         * Viewbox.Stretch – 子元素在 Viewbox 内的拉伸格局 [System.Windows.Media.Stretch 枚举]
         *     Stretch.None – 不做管理。不做别的拉伸管理,填充内容保持原来大小
         *     Stretch.Fill – 充满。调节填充内容,以充满整个容器,填充内容比例改为容器比例
         *     Stretch.Uniform – 等比适应。调解填充内容,以契合容器尺寸,填充内容会做等比例调解(暗许值)
         *         要是填充内容与容器比例不一致,那么填充内容调度的结果为:
     *       使得填充内容的宽与容器的宽相等,大概 填充内容的高与容器的高相等。填充内容会被完全展现
         *     Stretch.UniformToFill – 等比充满。调解填充内容,以符合容器尺寸,填充内容会做等比例调度
         *         若是填充内容与容器比例分化样,那么填充内容调治的结果为:
     *      使得填充内容的宽与容器的宽相等,并且 填充内容的高与容器的高相等。填充内容会被做相应的剪裁
         */
        private void stretchNone(object sender, RoutedEventArgs e)
        {
            viewbox.Stretch = Stretch.None;
            ShowResult();
        }
        private void stretchFill(object sender, RoutedEventArgs e)
        {
            viewbox.Stretch = Stretch.Fill;
            ShowResult();
        }
        private void stretchUniform(object sender, RoutedEventArgs e)
        {
            viewbox.Stretch = Stretch.Uniform;
            ShowResult();
        }
        private void stretchUniformToFill(object sender, RoutedEventArgs e)
        {
            viewbox.Stretch = Stretch.UniformToFill;
            ShowResult();
        }

public static int getCount()
{
string sql = “select count(*) from Users”;
return (int)DbConHelper.ExecuteScalar(sql);

        /*
         * Viewbox.StretchDirection – 子成分在 Viewbox 内的缩放格局 [System.Windows.Controls.StretchDirection 枚举]
         *     StretchDirection.UpOnly – 当子元素小于 Viewbox 时,子成分会加大
         *     StretchDirection.DownOnly – 当子成分大于 Viewbox 时,子成分会压缩
         *     StretchDirection.Both – 不做其余管理(暗中认可值)
         */
        private void stretchDirectionUpOnly(object sender, RoutedEventArgs e)
        {
            viewbox.StretchDirection = StretchDirection.UpOnly;
            ShowResult();
        }
        private void stretchDirectionDownOnly(object sender, RoutedEventArgs e)
        {
            viewbox.StretchDirection = StretchDirection.DownOnly;
            ShowResult();
        }
        private void stretchDirectionBoth(object sender, RoutedEventArgs e)
        {
            viewbox.StretchDirection = StretchDirection.Both;
            ShowResult();
        }

}

        /*
         * Viewbox.HorizontalAlignment – 子成分在 Viewbox 内的品位方向的对齐方式 [System.Windows.HorizontalAlignment 枚举]
         *      Center, Left, Right, Stretch(默认值)
         */
        private void horizontalAlignmentCenter(object sender, RoutedEventArgs e)
        {
            viewbox.HorizontalAlignment = HorizontalAlignment.Center;
            ShowResult();
        }
        private void horizontalAlignmentLeft(object sender, RoutedEventArgs e)
        {
            viewbox.HorizontalAlignment = HorizontalAlignment.Left;
            ShowResult();
        }
        private void horizontalAlignmentRight(object sender, RoutedEventArgs e)
        {
            viewbox.HorizontalAlignment = HorizontalAlignment.Right;
            ShowResult();
        }
        private void horizontalAlignmentStretch(object sender, RoutedEventArgs e)
        {
            viewbox.HorizontalAlignment = HorizontalAlignment.Stretch;
            ShowResult();
        }

        /*
         * Viewbox.VerticalAlignment – 子成分在 Viewbox 内的垂直方向的对齐情势 [System.Windows.VerticalAlignment 枚举]
         *      Center, Top, Bottom, Stretch(默认值)
         */
        private void verticalAlignmentCenter(object sender, RoutedEventArgs e)
        {
            viewbox.VerticalAlignment = VerticalAlignment.Center;
            ShowResult();
        }
        private void verticalAlignmentTop(object sender, RoutedEventArgs e)
        {
            viewbox.VerticalAlignment = VerticalAlignment.Top;
            ShowResult();
        }
        private void verticalAlignmentBottom(object sender, RoutedEventArgs e)
        {
            viewbox.VerticalAlignment = VerticalAlignment.Bottom;
            ShowResult();
        }
        private void verticalAlignmentStretch(object sender, RoutedEventArgs e)
        {
            viewbox.VerticalAlignment = VerticalAlignment.Stretch;
            ShowResult();
        }
    }
}

2、RichTextBox 的 Demo
RichTextBoxDemo.xaml

图片 5图片 6代码

<navigation:Page x:Class=”Silverlight40.Control.RichTextBoxDemo” 
           xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” 
           xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” 
           xmlns:d=”http://schemas.microsoft.com/expression/blend/2008
           xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006
           xmlns:navigation=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation”
           Title=”RichTextBoxDemo Page”>
    <StackPanel HorizontalAlignment=”Left”>
        
        <StackPanel Background=”AntiqueWhite” Orientation=”Horizontal”>
            <ComboBox x:Name=”cmbFontSize” FontSize=”{Binding SelectedItem.FontSize, RelativeSource={RelativeSource Self}}” SelectionChanged=”cmbFontSize_SelectionChanged”>
                <ComboBoxItem Content=”16″ Tag=”16″ FontSize=”16″ IsSelected=”True” />
                <ComboBoxItem Content=”48″ Tag=”48″ FontSize=”48″ />
            </ComboBox>
            <ComboBox x:Name=”cmbFontFamily” FontFamily=”{Binding SelectedItem.FontFamily, RelativeSource={RelativeSource Self}}” SelectionChanged=”cmbFontFamily_SelectionChanged”>
                <ComboBoxItem Content=”Arial” Tag=”Arial” FontFamily=”Arial” IsSelected=”True” />
                <ComboBoxItem Content=”Verdana” Tag=”Verdana” FontFamily=”Verdana” />
            </ComboBox>
            <Button Name=”btnBold” Content=”加粗” Click=”btnBold_Click” />
            <Button Name=”btnItalic” Content=”斜体” Click=”btnItalic_Click” />
            <Button Name=”btnUnderline” Content=”下划线” Click=”btnUnderline_Click” />
            <Button Name=”btnHyperlink” Content=”插入一级链接的 德姆o” Click=”btnHyperlink_Click” />
            <Button Name=”btnUIElement” Content=”插入 UIElement 的 Demo” Click=”btnUIElement_Click” />
            <ToggleButton Name=”btnXaml” Content=”xaml” Checked=”btnXaml_Checked” Unchecked=”btnXaml_Checked” />
            <ToggleButton Name=”btnPreview” Content=”预览” Checked=”btnPreview_Checked” Unchecked=”btnPreview_Checked” />
            <Button Name=”btnTextPointer德姆o” Content=”TextPointer 的 德姆o (将光标当前所在地点到文本结尾的文字全变为紫藤色)” Click=”btnTextPointer德姆o_Click” />
        </StackPanel>
        
        <Grid Width=”600″ Height=”400″>
            <RichTextBox Name=”richTextBox” VerticalScrollBarVisibility=”Auto”>
                <Paragraph>
                    webabcd
                </Paragraph>
                <Paragraph>
                    <Span>webabcd</Span>
                    <LineBreak />
                    <Bold>webabcd</Bold>
                    <LineBreak />
                    <Italic>webabcd</Italic>
                    <LineBreak />
                    <Underline>webabcd</Underline>
                    <LineBreak />
                    <Run FontFamily=”Arial” FontSize=”20″ FontStretch=”Normal” FontStyle=”Italic” FontWeight=”Bold” Foreground=”Red” TextDecorations=”underline” Text=”webabcd” />
                    <LineBreak />
                    <Hyperlink TargetName=”_black” NavigateUri=”http://webabcd.cnblogs.com/"&gt;webabcd&lt;/Hyperlink&gt;
                    <LineBreak />
                    <InlineUIContainer>
                        <Image Source=”/Resource/Logo.jpg” Height=”拾0″ Width=”100″ ToolTipService.ToolTip=”笔者是提示” />
                    </InlineUIContainer>
                </Paragraph>
            </RichTextBox>
            <TextBox Name=”txtXaml” TextWrapping=”Wrap” VerticalScrollBarVisibility=”Auto” Visibility=”Collapsed” />
        </Grid>
        
        <TextBlock Name=”lblMsg” />
        
    </StackPanel>
</navigation:Page>

RichTextBoxDemo.xaml.cs

图片 7图片 8代码

/*
 * RichTextBox – 编辑器。用于显示或编辑文本、超链、图片、UI元素等
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Windows.Media.Imaging;

namespace Silverlight40.Control
{
    public partial class RichTextBoxDemo : Page
    {
        public RichTextBoxDemo()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            /*
             * RichText博克斯 的原委结构表明如下:
             * 
             * Block – 抽象类。块级内容的基类
             *     Paragraph – 段落,包括1组内联成分。承袭自 Block
             * Inline – 抽象类。内联成分的基类
             *     Run – 文本。继承自 Inline
             *     LineBreak – 换行。继承自 Inline
             *     Span – 文本。继承自 Inline
             *         Hyperlink – 超链接。继承自 Span
             *         Bold – 加粗。继承自 Span
             *         Italic – 斜体。继承自 Span
             *         Underline – 下划线。继承自 Span
             *     InlineUIContainer – 用于承载 UIElement 类型的对象。承袭自 Span
             * TextElement – TextElement是 Inline 的基类,能够对其安装如下属性
             *     FontSize – 字体大小
             *     FontFamily – 字体名称
             *     Foreground – 字体颜色(因为 xaml 属性仅支持能够象征为3个字符串的属性值。所以这里只好动用 SolidColorBrush,而不可能使用 LinearGradientBrush 之类的)
             *     FontWeight – 笔画粗细
             *     FontStyle – 是还是不是斜体
             *     FontStretch – 字体的拉伸程度(须求字体补助)
             */

            /* 
             * Paragraph.Inlines – 段落所包蕴的内联成分的成团
             * RichTextBox.Blocks – RichTextBox 中的块级成分的集结
             * RichTextBox.Xaml – RichTextBox 中的内容的 xaml 代码
             */

            Bold bold = new Bold();
            bold.Inlines.Add(“web”);

            LineBreak lineBreak = new LineBreak();

            Run run = new Run();
            run.Text = “abcd”;
            
            Paragraph paragraph = new Paragraph();
            paragraph.Inlines.Add(bold);
            paragraph.Inlines.Add(lineBreak);
            paragraph.Inlines.Add(run);

            richTextBox.Blocks.Add(paragraph);
        }

        /*
         * RichTextBox.Selection – 获取 RichTextBox 中的选中内容,重返叁个 TextSelection 类型的靶子
         * TextSelection.ApplyPropertyValue(DependencyProperty formattingProperty,    Object value) – 为当选的内容内定其格式的性质和值
         *     DependencyProperty formattingProperty – 格式的属性
         *     Object value – 格式的质量的值
         * TextSelection.Text – 选中的内容中的纯文本内容
         * TextSelection.Xaml – 选中的内容的 xaml 代码
         * TextSelection.Insert() – 把当下选中的内容替换成钦命的 TextElement
         * 以下分别举个例子怎么样设置选中文本的字体大小、字体名称、加粗、斜体、下划线
         */
        private void cmbFontSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (richTextBox != null && richTextBox.Selection.Text.Length > 0)
            {
                richTextBox.Selection.ApplyPropertyValue(Run.FontSizeProperty, double.Parse((cmbFontSize.SelectedItem as ComboBoxItem).Tag.ToString()));
            }
        }
        private void cmbFontFamily_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (richTextBox != null && richTextBox.Selection.Text.Length > 0)
            {
                richTextBox.Selection.ApplyPropertyValue(Run.FontFamilyProperty, new FontFamily((cmbFontFamily.SelectedItem as ComboBoxItem).Tag.ToString()));
            }
        }
        private void btnBold_Click(object sender, RoutedEventArgs e)
        {
            if (richTextBox.Selection.Text.Length > 0)
            {
                if (richTextBox.Selection.GetPropertyValue(Run.FontWeightProperty) is FontWeight && ((FontWeight)richTextBox.Selection.GetPropertyValue(Run.FontWeightProperty)) == FontWeights.Normal)
                    richTextBox.Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Bold);
                else
                    richTextBox.Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Normal);
            }
        }
        private void btnItalic_Click(object sender, RoutedEventArgs e)
        {
            if (richTextBox.Selection.Text.Length > 0)
            {
                if (richTextBox.Selection.GetPropertyValue(Run.FontStyleProperty) is FontStyle && ((FontStyle)richTextBox.Selection.GetPropertyValue(Run.FontStyleProperty)) == FontStyles.Normal)
                    richTextBox.Selection.ApplyPropertyValue(Run.FontStyleProperty, FontStyles.Italic);
                else
                    richTextBox.Selection.ApplyPropertyValue(Run.FontStyleProperty, FontStyles.Normal);
            }
        }
        private void btnUnderline_Click(object sender, RoutedEventArgs e)
        {
            if (richTextBox.Selection.Text.Length > 0)
            {
                if (richTextBox.Selection.GetPropertyValue(Run.TextDecorationsProperty) == null)
                    richTextBox.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, TextDecorations.Underline);
                else
                    richTextBox.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, null);
            }
        }

        /*
         * TextSelection.Insert() – 把当前当选的剧情替换来内定的 TextElement
         * Hyperlink – 一个用来展示超链接的内联成分。Hyperlink承继自Span,Span继承自Inline,Inline承接自TextElement
         * 以下举个例子怎么着插入超链接(要在 RichTextBox 使超链接有效,供给将 RichTextBox 设置为突显状态)
         */
        private void btnHyperlink_Click(object sender, RoutedEventArgs e)
        {
            Hyperlink hyperlink = new Hyperlink();
            hyperlink.TargetName = “_blank”;
            hyperlink.NavigateUri = new Uri(“http://webabcd.cnblogs.com/“);
            hyperlink.Inlines.Add(“webabcd blog”);
            richTextBox.Selection.Insert(hyperlink);
        }

        /*
         * InlineUIContainer – 贰个器皿,能够承继任何 UIElement 类型的目的。InlineUIContainer承继自Inline
         * 以下比方怎么样插入图片
         */
        private void btnUIElement_Click(object sender, RoutedEventArgs e)
        {
            Image img = new Image();
            img.Source = new BitmapImage(new Uri(“/Resource/Logo.jpg”, UriKind.Relative));
            img.Width = 100;
            img.Height = 100;

            InlineUIContainer container = new InlineUIContainer();
            container.Child = img;

            richTextBox.Selection.Insert(container);
        }

        /*
         * RichTextBox.Xaml – RichTextBox 中的内容的 xaml 代码
         * 以下比如怎样在“呈现形式”和“代码格局”之间切换
         */
        private void btnXaml_Checked(object sender, RoutedEventArgs e)
        {
            if (btnXaml.IsChecked.Value)
            {
                txtXaml.Text = richTextBox.Xaml;
                txtXaml.Visibility = Visibility.Visible;
            }
            else
            {
                richTextBox.Xaml = txtXaml.Text;
                txtXaml.Visibility = Visibility.Collapsed;
            }
        }

        /*
         * RichText博克斯.IsReadOnly – 钦点是或不是能够在 RichTextBox 中编辑内容
         *     true – 显示情势
         *     false – 编辑形式(此形式下能够通过连忙键的主意来支撑撤消 Ctrl+Z 和重做 Ctrl+Y 操作)
         * 以下举例怎么样预览 RichTextBox 中的内容(注:唯有在体现方式中中国足球球组织拔尖联赛链接才生效)
         */
        private void btnPreview_Checked(object sender, RoutedEventArgs e)
        {
            richTextBox.IsReadOnly = btnPreview.IsChecked.Value;
        }

        private void btnTextPointerDemo_Click(object sender, RoutedEventArgs e)
        {
            /*
             * TextPointer – 表示 RichTextBox 中的三个职位
             * 插入地方(Insertion Position)的定义:
             *     TextPointer 出现在剧情中的字符之间则为插入地方
             *     TextPointer 出现在概念内容结构的成分标志之间,则此职责不是插入地方。举例,五个相邻段落标志(即前七个段落的甘休标识与下一个段子的初步标识)之间的岗位就是一个实惠的 TextPointer 地点,但不是插入地点
             * TextPointer.CompareTo(TextPointer tp) – 当前 TextPointer 位于钦命的 TextPointer 从前则为 -一,之后则为 一,同样则为 0
             * TextPointer.IsAtInsertionPosition – 当前 TextPointer 是或不是是1个插入地方
             * TextPointer.GetNextInsertionPosition(LogicalDirection direction) – 获取当前 TextPointer 的按内定的逻辑方向的下3个插入地方
             *     LogicalDirection – 逻辑方向 [System.Windows.Documents.LogicalDirection 枚举]
             *         LogicalDirection.Forward – 向前
             *         LogicalDirection.Backward – 向后
             * TextPointer.GetPositionAtOffset(int offset, LogicalDirection direction) – 获取当前 TextPointer 的按钦命的逻辑方向偏移了内定值的 TextPointer
             * TextPointer.Parent – 蕴涵当前 TextPointer 的容器。譬喻,文字的 Parent 是 run ;RichTextBox.ContentEnd 的 Parent 是 RichTextBox
             * 
             * RichTextBox.ContentStart – RichTextBox 内容的启幕的 TextPointer(确定不是插入位置)
             * RichTextBox.ContentEnd – RichTextBox 内容的结尾的 TextPointer(分明不是插入地方)
             * RichTextBox.GetPositionFromPoint(Point point) – 获取离钦定 Point 近来的插入地点
             * RichTextBox.Selection – 获取 RichTextBox 中的选中内容,重回三个 TextSelection 类型的靶子
             * TextSelection.Start – 选中内容的开始 TextPointer
             * TextSelection.End – 选中内容的发端 TextPointer
             * TextSelection.Select(TextPointer tp一, TextPointer tp二) – 钦赐多个 TextPointer 来更新选中内容
             * 
             * 在 RichTextBox 中被视为1个标识的有:TextElement 的始发或收尾标志;InlineUIContainer 中的 UIElement 元素;Run 中的字符
             */

            // 将光标当前所在地方到文本结尾的文字全变为高粱红
            TextPointer currentPointer = richTextBox.Selection.Start;
            TextPointer endPointer = richTextBox.ContentEnd.GetNextInsertionPosition(LogicalDirection.Backward);
            richTextBox.Selection.Select(currentPointer, endPointer);
            richTextBox.Selection.ApplyPropertyValue(Run.ForegroundProperty, Colors.Green);

            // 将光标当前所在地点到文本结尾的文字消息输出到页面上
            while (currentPointer.CompareTo(endPointer) == -1)
            {
                string currentChar = “”;

                TextPointer nextPointer = currentPointer.GetNextInsertionPosition(LogicalDirection.Forward);
                if (nextPointer != null)
                {
                    richTextBox.Selection.Select(currentPointer, nextPointer);
                    if (richTextBox.Selection.Text.Length != 0)
                        currentChar = richTextBox.Selection.Text;
                }

                lblMsg.Text += currentChar;

                currentPointer = currentPointer.GetNextInsertionPosition(LogicalDirection.Forward);
            }
        }
    }
}

OK
[源码下载]

相关文章