WPF 里面的 Run .感觉这名称真没取好,application 里面有个 run, textblock 里面也有个.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;
using System.Reflection;
using System.Windows.Input;
using System.Windows.Documents;
namespace WpfApplication1
{
class Test : Window
{
string str=null;
[STAThread]
static void Main()
{
Application app = new Application();
app.Run(new Test());
}
/// <summary>
/// 有些夸张,关键是每个字都可以加事件。。Run 还是继承自 UElement;
/// </summary>
public Test()
{
Content = str;
Title = "Format the Text";
TextBlock txt = new TextBlock();
txt.FontFamily = new System.Windows.Media.FontFamily("微软雅黑");
txt.FontSize = 48;
txt.HorizontalAlignment = HorizontalAlignment.Center;
txt.VerticalAlignment = VerticalAlignment.Center;
Content = txt;
string strquote = "To be,or not to be, that is the question"+Environment.NewLine+"Click Me!!";
string[] strwords = strquote.Split();
foreach (var item in strwords)
{
Run run = new Run(item);
run.MouseDown += new MouseButtonEventHandler(run_MouseDown);
txt.Inlines.Add(run);
txt.Inlines.Add(" ");
}
Content = txt;
}
/// <summary>
/// 鼠标按下事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void run_MouseDown(object sender, MouseButtonEventArgs e)
{
Run run = sender as Run;
if (e.ChangedButton == MouseButton.Left)
{
run.FontStyle = run.FontStyle == FontStyles.Italic ? FontStyles.Normal : FontStyles.Italic;
}
if (e.ChangedButton == MouseButton.Right)
{
run.FontWeight= run.FontWeight == FontWeights.Bold ? FontWeights.Normal : FontWeights.Bold;
}
}
/// <summary>
/// 字符输入
/// </summary>
/// <param name="e"></param>
protected override void OnTextInput(TextCompositionEventArgs e)
{
base.OnTextInput(e);
str = (string)Content;
if (e.Text == "\b")
{
if (str.Length > 0)
{
str = str.Substring(0, str.Length - 1);
}
}
else
{
str += e.Text;
}
//Content = str;
}
}
}