您的位置:首页 > 其它

[WPF] TextBlock小范例

2010-09-07 17:17 218 查看




using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Documents;

namespace Cloud.FormatTheText
{
    public class FormatTheText : Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new FormatTheText());
        }

        public FormatTheText()
        {
            this.Title = "Cloud Orz";
            TextBlock txt = new TextBlock();
            txt.FontSize = 32;
            Run run = new Run("This is some ");
            run.MouseDown += new MouseButtonEventHandler(run_MouseDown);
            run.Foreground = Brushes.Red;
            txt.Inlines.Add(run);
            txt.Inlines.Add(new Italic(new Run("italic")));
            txt.Inlines.Add(" text, and this is some ");
            txt.Inlines.Add(new Bold(new Run("bold")));
            txt.Inlines.Add(" text, and this is some ");
            txt.Inlines.Add(new Bold(new Italic(new Run("bold italic"))));
            txt.Inlines.Add(" text.");
            txt.TextWrapping = TextWrapping.Wrap;
            this.Content = txt;
        }

        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;
        }
    }
}




这些代码,就是很单纯的建立一个TextBlock,然后放进Window的Content property

若是直接将string放入Content property, 将会先建立一个TextBlock,以显示出字串

同时示范了,如何安装事件到Run对象中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: