(WPF学习记录)第三章 Content的概念

来源:互联网 发布:2016网络知识竞赛答题 编辑:程序博客网 时间:2024/05/21 03:28

Window类有超过100个公开的属性,其中一些(如Title等)相当重要,但迄今为止,Window最重要的属性是Content。

我们可以将Content设定成一个字符串、位图、矢量图、按钮、滚动条或者是WPF所支持的50多个控件。我们几乎可以将Content设定成任何东西。

第01个小程序:显示文本(DisplaySomeText.cs)

在客户区显示字符串。

  1. using System;
  2. using System.Windows;
  3. using System.Windows.Input;
  4. using System.Windows.Media;
  5. namespace Chapter03
  6. {
  7.     public class DisplaySomeText : Window
  8.     {
  9.         [STAThread]
  10.         public static void Main()
  11.         {
  12.             Application app = new Application();
  13.             app.Run(new DisplaySomeText());
  14.         }
  15.         public DisplaySomeText()
  16.         {
  17.             Title = "显示文字";
  18.             Width = 640;
  19.             Height = 480;
  20.             WindowStartupLocation = WindowStartupLocation.CenterScreen;
  21.             Content = "将进酒,杯莫停!";            //显示内容
  22.             FontFamily = new FontFamily("华文行楷"); //字体样式
  23.             FontSize = 32;                           //字体大小
  24.             FontStyle = FontStyles.Italic;           //斜体
  25.             FontWeight = FontWeights.Bold;           //粗体
  26.             Brush brush1 = new LinearGradientBrush(Colors.Silver,Colors.White,
  27.                 new Point(0,0),new Point(1,1));
  28.             Brush brush2 = new LinearGradientBrush(Colors.Red, Colors.Blue,
  29.                 new Point(0, 0), new Point(1, 1));
  30.             Background = brush1;         //背景色
  31.             Foreground = brush2;          //前景色。字体颜色
  32.             SizeToContent = SizeToContent.WidthAndHeight; //窗口大小根据文字内容尺寸作调整
  33.             ResizeMode = ResizeMode.NoResize;             //窗口大小调整方式(NoResize表示不可更改)
  34.         }
  35.     }
  36. }

第02个小程序:按钮记录(RecordKeystrokes.cs)

  1. using System;
  2. using System.Windows;
  3. using System.Windows.Input;
  4. using System.Windows.Media;
  5. namespace Chapter03
  6. {
  7.     public class RecordKeystrokes : Window
  8.     {
  9.         string str = "";  //定义字符串
  10.         [STAThread]
  11.         public static void Main()
  12.         {
  13.             Application app = new Application();
  14.             app.Run(new RecordKeystrokes());
  15.         }
  16.         public RecordKeystrokes()
  17.         {
  18.             Title = "按键记录";
  19.             //Content = "";
  20.         }
  21.         protected override void OnTextInput(TextCompositionEventArgs args)
  22.         {
  23.             base.OnTextInput(args);
  24.             //string str = Content as string;
  25.             
  26.             //BackSpace键时
  27.             if (args.Text == "/b")
  28.             {
  29.                 if (str.Length > 0)
  30.                     str = str.Substring(0, str.Length - 1);
  31.             }
  32.             else
  33.             {
  34.                 str += args.Text;
  35.             }
  36.             Content = str;   //Content为指定字符串
  37.         }
  38.     }
  39. }

运行后,敲击键盘,客户区会显示按键相应的字符。类似于第一章的TypeYourTitle程序,不过这里还可以Enter(换行)和Tab(跳格)。

现在把这个程序作下修改:

  1. using System;
  2. using System.Windows;
  3. using System.Windows.Input;
  4. using System.Windows.Media;
  5. using System.Text;
  6. namespace Chapter03
  7. {
  8.     public class RecordKeystrokes : Window
  9.     {
  10.         StringBuilder build = new StringBuilder("呵呵!");
  11.         [STAThread]
  12.         public static void Main()
  13.         {
  14.             Application app = new Application();
  15.             app.Run(new RecordKeystrokes());
  16.         }
  17.         public RecordKeystrokes()
  18.         {
  19.             Title = "按键记录";
  20.             Content = build;
  21.         }
  22.         protected override void OnTextInput(TextCompositionEventArgs args)
  23.         {
  24.             base.OnTextInput(args);
  25.             
  26.             //BackSpace键时
  27.             if (args.Text == "/b")
  28.             {
  29.                 if (build.Length > 0)
  30.                     build.Remove(build.Length - 1, 1);
  31.             }
  32.             else
  33.             {
  34.                 build.Append(args.Text);
  35.             }
  36.             //Content = null;
  37.             Content = build;
  38.         }
  39.     }
  40. }

与前一代码相比,换了种方式,功能完全一样。

但此时,程序却不能正常执行。运行后,客户区只会出现build初始化时的“呵呵!”,然后不管我们怎么敲击键盘它就是不再多显示一个字符。为什么呢?

原来窗口够聪明,它知道我指定相同的对象build给Cotent,就偷懒地不更新了,这时我们在OnTextInput()里的Content = build前加一句“Content = null;”,改变下Content的设定,让窗口活动下脑筋,它就回过神来了,程序也就恢复正常。

第03个小程序:显示图片(ShowMyPicture .cs)

  1. using System;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Input;
  5. using System.Windows.Media;
  6. using System.Windows.Media.Imaging;
  7. namespace Chpter03
  8. {
  9.     class ShowMyPicture : Window
  10.     {
  11.         [STAThread]
  12.         public static void Main()
  13.         {
  14.             Application app = new Application();
  15.             app.Run(new ShowMyFace());
  16.         }
  17.         public ShowMyPicture()
  18.         {
  19.             Title = "显示图片";
  20.             Width = 384;
  21.             Height = 288;
  22.             Background = new LinearGradientBrush(Colors.Red,Colors.Blue,
  23.                 new Point(0,0),new Point(1,1));
  24.             Uri uri = new Uri(                                            //建立Uri对象,用来表示位图的位置
  25.                 "http://profile.csdn.net/changjiangboy/picture/1.jpg");
  26.             //Uri uri = new Uri("file://C://Documents and Settings//Administrator//桌面//001.jpg");
  27.             BitmapImage bitmap = new BitmapImage(uri);                    //将uri载入内存
  28.             Image img = new Image();                                      //图像Image实例
  29.             img.Source = bitmap;                                          //设置图像资源
  30.             img.Stretch = Stretch.None;                          //图像拉伸方式
  31.             //img.Margin = new Thickness(10,10,10,10);                      //图像与窗口边界距离
  32.             img.Opacity = 0.6;                                            //图像透明度
  33.             img.LayoutTransform = new RotateTransform(30);                //顺时针旋转30度
  34.             //图像放在客户区左上角
  35.             //img.HorizontalAlignment = HorizontalAlignment.Left;
  36.             //img.VerticalAlignment = VerticalAlignment.Top;
  37.             Content = img;                                                //实例img指给Content
  38.         }
  39.     }
  40. }

效果如下

第04个小程序:绘制椭圆(ShapeAnEllipse .cs)

  1. using System;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Input;
  5. using System.Windows.Media;
  6. using System.Windows.Shapes;
  7. namespace Chapter03
  8. {
  9.     class ShapeAnEllipse : Window
  10.     {
  11.         [STAThread]
  12.         public static void Main()
  13.         {
  14.             Application app = new Application();
  15.             app.Run(new ShapeAnEllipse());
  16.         }
  17.         public ShapeAnEllipse()
  18.         {
  19.             Title = "绘制椭圆";
  20.             Width = 384;
  21.             Height = 288;
  22.             Background = new LinearGradientBrush(Colors.Red, Colors.Blue,
  23.                 new Point(0, 0), new Point(1, 1)); 
  24.             Ellipse elips = new Ellipse();     //定义椭圆对象
  25.             elips.Width = 320;                 //椭圆宽度
  26.             elips.Height = 240;                //椭圆高度
  27.             elips.Fill = Brushes.DimGray;      //椭圆内部填充方式
  28.             elips.StrokeThickness = 24;        //椭圆轮廓宽度
  29.             //把椭圆放置在左下角
  30.             elips.HorizontalAlignment = HorizontalAlignment.Left;
  31.             elips.VerticalAlignment = VerticalAlignment.Bottom;
  32.             elips.Stroke = new LinearGradientBrush(       //椭圆轮廓绘制方式
  33.                 Colors.CadetBlue, Colors.Chocolate,
  34.                 new Point(1, 0), new Point(0, 1));
  35.             Content = elips;
  36.         }
  37.     }
  38. }

运行效果如下

第05个小程序:格式化文本(FormatTheText) 

  1. using System;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Input;
  5. using System.Windows.Media;
  6. using System.Windows.Documents;
  7. namespace Chapter03
  8. {
  9.     class FormatTheText : Window
  10.     {
  11.         [STAThread]
  12.         public static void Main()
  13.         {
  14.             Application app = new Application();
  15.             app.Run(new FormatTheText());
  16.         }
  17.         public FormatTheText()
  18.         {
  19.             Title = "格式化文本";
  20.             TextBlock txt = new TextBlock();
  21.             txt.FontSize = 32;
  22.             txt.Inlines.Add("这是");
  23.             txt.Inlines.Add(new Italic(new Run("斜体字")));
  24.             txt.Inlines.Add(",这是");
  25.             txt.Inlines.Add(new Bold(new Run("粗体字")));
  26.             txt.Inlines.Add(",这是");
  27.             txt.Inlines.Add(new Bold(new Italic(new Run("斜体粗字"))));
  28.             txt.Inlines.Add("。");
  29.             txt.TextWrapping = TextWrapping.Wrap;        //文本换行方式
  30.             Content = txt;
  31.         }
  32.     }
  33. }

程序用来组合TextBlock的Inlines集,InlineCollection类形的Inlines实现了Add方法,可以加入字符串对象、Inline对象、以及UIElement对象。然而,Bold和Italic构造接受Inline对象,而不接受字符串对象,所以程序先为每个Bold或Italic对象使用Run构造函数。

第06个小程序:粗体和斜体(ToggleBoldAndItalic.cs)

  1. using System;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Documents;
  5. using System.Windows.Input;
  6. using System.Windows.Media;
  7. namespace Chapter03
  8. {
  9.     public class ToggleBoldAndItalic : Window
  10.     {
  11.         [STAThread]
  12.         public static void Main()
  13.         {
  14.             Application app = new Application();
  15.             app.Run(new ToggleBoldAndItalic());
  16.         }
  17.         public ToggleBoldAndItalic()
  18.         {
  19.             Title = "粗体否?斜体否?";
  20.             TextBlock text = new TextBlock();
  21.             text.FontSize = 32;
  22.             text.HorizontalAlignment = HorizontalAlignment.Center;
  23.             text.VerticalAlignment = VerticalAlignment.Center;
  24.             Content = text;
  25.             string strQuote = "嘿! 你到底想怎么样?!";
  26.             string[] strWords = strQuote.Split();       //分隔字符串
  27.             foreach (string str in strWords)
  28.             {
  29.                 Run run = new Run(str);
  30.                 run.MouseDown += RunOnMouseDown;
  31.                 text.Inlines.Add(run);
  32.                 text.Inlines.Add(" ");
  33.             }
  34.         }
  35.         void RunOnMouseDown(object sender, MouseButtonEventArgs args)
  36.         {
  37.             Run run = sender as Run;
  38.             //鼠标左击时,斜体切换
  39.             if (args.ChangedButton == MouseButton.Left)
  40.                 run.FontStyle = run.FontStyle == FontStyles.Italic ?
  41.                     FontStyles.Normal : FontStyles.Italic;
  42.             //鼠标右击时,粗体切换
  43.             if (args.ChangedButton == MouseButton.Right)
  44.                 run.FontWeight = run.FontWeight == FontWeights.Bold ?
  45.                     FontWeights.Normal : FontWeights.Bold;
  46.         }
  47.     }
  48. }

Run类实例对象包含一连串格式化或未格式化文本的内联级别的流内容元素。

第07个小程序:显示椭圆(RenderTheGraphic.cs)

  1. using System;
  2. using System.Windows;
  3. using System.Windows.Media;
  4. namespace Chapter03
  5. {
  6.     class RenderTheGraphic : Window
  7.     {
  8.         [STAThread]
  9.         public static void Main()
  10.         {
  11.             Application app = new Application();
  12.             app.Run(new RenderTheGraphic());
  13.         }
  14.         public RenderTheGraphic()
  15.         {
  16.             Title = "Render the Graphic";
  17.             SimpleEllipse elips = new SimpleEllipse();
  18.             Content = elips;
  19.         }
  20.     }
  21.     class SimpleEllipse : FrameworkElement
  22.     {
  23.         protected override void OnRender(DrawingContext dc)
  24.         {
  25.             dc.DrawEllipse(Brushes.Blue,             //填充椭圆的画笔      
  26.                 new Pen(Brushes.Red, 24),            //绘制椭圆笔画的笔(颜色,宽度)
  27.                 new Point(RenderSize.Width / 2,      //椭圆的中心位置
  28.                     RenderSize.Height / 2),
  29.                 RenderSize.Width / 2 - 12,           //椭圆的水平半径
  30.                 RenderSize.Height / 2 - 12);         //椭圆的垂直半径
  31.         }
  32.     }
  33. }

窗口的Content属性想要的是继承自UIElement类的实例,因为此类定义一个OnRender的方法,负责在屏幕上显示此对象。

这里继承自FrameworkElement(它直接继承自UIElement)的SimpleEllipse 类重载OnRender方法,获得DrawingContext 对象,保留DrawEllipse信息。然后在构造函数中实例化SimpleEllipse 对象,并将对象指给Content。

原创粉丝点击