分页作用,三思而行Silverlight

[索引页]
[源码下载]

前台xaml文件

从长商议Silverlight(42) – 4.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=”18″ 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 4.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;

澳门1495娱乐 1澳门1495娱乐 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.Horizontal阿里gnment 属性 –>
            <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 内只可以有四个子成分 –>
                    <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

澳门1495娱乐 3澳门1495娱乐 4代码

}
}

/*
 * Viewbox – 三个器皿控件,其内只可以有多个子成分。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.Horizontal阿里gnment – 子元素在 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

澳门1495娱乐 5澳门1495娱乐 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=”100″ 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

澳门1495娱乐 7澳门1495娱乐 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)
        {
            /*
             * RichTextBox 的内容结构表达如下:
             * 
             * Block – 抽象类。块级内容的基类
             *     Paragraph – 段落,包罗一组内联成分。承袭自 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 属性仅援助能够表示为三个字符串的属性值。所以这边不得不采纳 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 操作)
         * 以下比方怎样预览 RichText博克斯 中的内容(注:唯有在展现方式中超链接才生效)
         */
        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 在此之前则为 -1,之后则为 1,同样则为 0
             * TextPointer.IsAtInsertionPosition – 当前 TextPointer 是不是是三个插入地方
             * TextPointer.GetNextInsertionPosition(LogicalDirection direction) – 获取当前 TextPointer 的按钦命的逻辑方向的下贰个安顿地方
             *     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(料定不是插入地方)
             * RichText博克斯.ContentEnd – RichText博克斯 内容的末段的 TextPointer(肯定不是插入地方)
             * RichTextBox.GetPositionFromPoint(Point point) – 获取离钦点 Point 近来的插入地方
             *澳门1495娱乐, RichTextBox.Selection – 获取 RichTextBox 中的选中内容,重回多少个 TextSelection 类型的指标
             * TextSelection.Start – 选中内容的起先 TextPointer
             * TextSelection.End – 选中内容的初叶 TextPointer
             * TextSelection.Select(TextPointer tp1, TextPointer tp2) – 钦定三个 TextPointer 来更新选中内容
             * 
             * 在 RichTextBox 中被视为一个标志的有: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
[源码下载]