Welcome

首页 / 软件开发 / Silverlight / Silverlight开发中的疑难杂症:如何实现一个EditorBox

Silverlight开发中的疑难杂症:如何实现一个EditorBox2011-04-13 博客园 yingqlEditorBox就是一个具有编辑和展示两种状态的TextBox,因为在最近的工作和学习项目中 ,多次碰到了需要将一个TextBox以编辑和展示两种不同的样式存在,于是就想到了制作一个 这样的控件来提高生产效率,同时也尝试一下自定义控件的开发。该控件包括如下功能:

l 能在编辑和展示状态之间切换;

l 可以设置是否能够编辑;

l 在展示状态双击控件,进入到编辑状态(如果支持编辑);

l 在编辑状态,输入完文本,回车后进入展示状态;

l 提供一个Text属性供外部使用;

l 能够设置展示状态下文本样式(设置指定区间的文本的字体、字体大小、字体颜色等) ;

基本的实现思路是这样的:首先,定义两个TemplatePart,分别为TextBox和TextBlock类 型,用来表示编辑框跟展示框,文本格式的处理通过动态计算所设置的格式,然后添加多个 Run元素来实现;然后,定一个两个TemplateVisualState,用来实现编辑状态和展示状态之 间的切换。附加的Attribute声明如下:

[TemplatePart(Name = "PART_Editor", Type = typeof(TextBox))]

[TemplatePart(Name = "PART_View", Type = typeof(TextBlock))]

[TemplateVisualState(Name = "Edit", GroupName = "CommonStates")]

[TemplateVisualState(Name = "View", GroupName = "CommonStates")]

为了使控件使用者能够对样式进行更好的控制,这里定义了一个TextFormat类,与单个的 样式设置对应,里面包括字体、字体大小、字体颜色、样式应用的起始索引、应用的总长度 ,具体的类实现如下:

TextFormat

/// <summary>
/// 文本格式
/// </summary>
public class TextFormat : DependencyObject
{
/// <summary>
/// 字体
/// </summary>
public FontFamily FontFamily
{
get { return (FontFamily)GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
public static readonly DependencyProperty FontFamilyProperty =
DependencyProperty.Register("FontFamily", typeof(FontFamily), typeof(TextFormat), new PropertyMetadata(default(FontFamily)));
/// <summary>
/// 字体大小
/// </summary>
public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
public static readonly DependencyProperty FontSizeProperty =
DependencyProperty.Register("FontSize", typeof(double), typeof(TextFormat), new PropertyMetadata(10.0));
/// <summary>
/// 字体颜色
/// </summary>
public Brush Foreground
{
get { return (Brush)GetValue(ForegroundProperty); }
set { SetValue(ForegroundProperty, value); }
}
public static readonly DependencyProperty ForegroundProperty =
DependencyProperty.Register("Foreground", typeof(Brush), typeof(TextFormat), new PropertyMetadata(new SolidColorBrush (Colors.Black)));
/// <summary>
/// 样式应用的起始索引
/// </summary>
public int StartIndex
{
get { return (int)GetValue(StartIndexProperty); }
set { SetValue(StartIndexProperty, value); }
}
public static readonly DependencyProperty StartIndexProperty =
DependencyProperty.Register("StartIndex", typeof(int), typeof(TextFormat), new PropertyMetadata(0));
/// <summary>
/// 样式应用的长度
/// </summary>
public int Length
{
get { return (int)GetValue(LengthProperty); }
set { SetValue(LengthProperty, value); }
}
public static readonly DependencyProperty LengthProperty =
DependencyProperty.Register("Length", typeof(int), typeof (TextFormat), new PropertyMetadata(0));
}
/// <summary>
/// 文本格式集合
/// </summary>
public class TextFormatCollection : ObservableCollection<TextFormat>
{
}