事缓则圆Silverlight澳门1495娱乐,分页功用

[索引页]
[源码下载]

前台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=”诺玛l”
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>
/// Edit.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.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);
}
澳门1495娱乐,/// <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.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

澳门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=”插入一级链接的 Demo” 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=”btnTextPointerDemo” Content=”TextPointer 的 Demo (将光标当前所在地方到文本结尾的文字全变为紫色)” Click=”btnTextPointerDemo_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(Service).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;
            }
        }

        /*
         * RichTextBox.IsReadOnly – 指定是还是不是可以在 RichTextBox 中编辑内容
         *     true – 突显方式
         *     false – 编辑方式(此格局下得以由此连忙键的不二法门来辅助撤除 Ctrl+Z 和重做 Ctrl+Y 操作)
         * 以下举例如何预览 RichTextBox 中的内容(注:唯有在显示情势中国足球协会顶尖联赛(Chinese Football Association Super League)链接才生效)
         */
        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(肯定不是插入地方)
             * RichTextBox.ContentEnd – RichTextBox 内容的终极的 TextPointer(肯定不是插入地方)
             * RichTextBox.GetPositionFromPoint(Point point) – 获取离指定 Point 近期的插入地点
             * 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
[源码下载]

相关文章