第四篇简单学习WPF中关于Content的概念。Content就是所要显示的内容,是用户能过接触到最直接的部分。你可以将Content设置为字符串,可以设置为位图,可以设置为矢量图。我们知道在WPF的世界里面都是矢量的…但是有一点需要注意的是,你只能设置一个东西给Content属性。
Content继承自ContentControl,ContentControl继承自Control。ContentControl好像就是为了定义Content和另外几个方法而存在的。Content被定义为object类型,暗示着它可以指定为任意对象,但是也不是所有的,因为你不能将它设置为另一个Window类型的对象。
在WPF中没有font,但是存在FontFamily,比如我们可以写:
FontFamily font=new FontFamily(”Times New Roman”);
FontSize=32; //使用设备无关单位,也就是1/96英寸。
FontStyle=FontStyles.Italic;
FontWeight=FontWeights.Bold;
在Content的世界中,分为2组对象,一组继承自UIElement,一组则不是,后面这一组的显示结果,是ToString()的返回值,而前面这一组则是利用OnRender()来显示。继承自UIElement的对象称之为Element.
书中的本章主要是讲解一些基本的属性:
1. SizeToContent: 这个用来设置window的窗口大小和content之间的关系
2. HorizontalAlignment, VertialAlignment用来设置水平和垂直距离
3. Margin设置element之间插入的距离,它可以指定为一个Thickness结构体
4. Stroke,StrokeThickness空间边缘的宽度
5. ActualWidth, ActualHeight:得到Element的实际Width和Height.
将content设置为Image,可以如下设置(Image有很多自己的属性我就不在这里一一讲解,MSDN都有详细的解释):
1. Uri uri=new Uri(“http://www.charlespetzold.com/PetzoldTattoo.jpg”); //如果是本地文件则使用file://+文件路径
BitmapImage image=new BitmapImage(uri);
Image img=new Image();
img.Source=image;
Content=img;
2. 如果你不想将uri作为参数,你必须使用BeginInit() 和EndInit();
Uri uri=new Uri(“http://www.charlespetzold.com/PetzoldTattoo.jpg”);
BitmapImage image=new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource=uri;
bitmap.EndInit();
Image img=new Image();
img.Source=image;
Content=img;
将Content设置为TextBlock, TextBlock对象直接继承自FrameworkElement, 它定义了Inlines属性,它是Inline的集合。 TextBlock属于System.Windows.Controls命名空间,而Inline属于System.Windows.Documents命名空间。 Inline继承自TextElement, TextElement继承自FrameworkContentElement, FrameworkContentElement继承自ContentElement. ContentControl和ContentElement是不同的,ContentControl是控件,它具有Content属性,可以显示自己,但是ContentElement需要自己是别的可以显示的对象的一部分才可以显示。如下:
TextBlock txt=new TextBlock();
txt.FontSize=32;
txt.Inlines.Add(“This is some ”);
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 let’s cap it off with some ”);
txt.Inlines.Add(new Bold(new Italic(new Run(“bold italic”))));
txt.Inlines.Add(“ text.”);
txt.TextWrapping=TextWrapping.Wrap;
Content=txt;
概念就介绍到这里。