精华内容
参与话题
问答
  • C# 中XML XAML WPF的学习

    2017-12-22 08:49:30
    XAML文档定义了WPF应用程序中组成窗口的面板、按钮和各种控件的布局。开发和美工设计界面可以独立起来。 XML:指可扩展标记语言(Extensible Markup Language),XML被设计为传输和存储数据,其焦点是数据的外观。 VS...

    WPF:Windows Presentation F

    XAML:Extensible Application Markup  Language

    XAML文档定义了WPF应用程序中组成窗口的面板、按钮和各种控件的布局。开发和美工设计界面可以独立起来。

    XML:指可扩展标记语言(Extensible Markup Language),XML被设计为传输和存储数据,其焦点是数据的外观。

    VS添加XML。新建项目中找不到XML此项文件,但在新建文件中有。

    <Window x:Class="WpfLearn.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
    
        </Grid>
    </Window>
    


    该文档仅含两个元素:顶级的window元素以及一个grid元素,window元素代表整个窗口,在Grid元素中可以放置所有控件。

    </Window>标签关闭了Window元素,文档结束。

    Title这行代码:每个特性对应Window类的一个单独属性。告诉WPF创建标题为“MainWindow”的窗口,并使窗口的大小为300*300单位。WPF中使用可进行缩放以适应不同显示器分辨率的设备无关单位。

    xmlns特性是XML中的一个特殊特性,它专门用来声明名称空间。这段标记声明了两个名称空间,在创建的所有WPF XAML文档中都会使用这两个名称空间:

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"是WPF核心名称空间。包含了所有WPF类,包括用来构建用户界面的控件,此处声明没有使用名称空间前缀,其成为整个文档的默认名称空间。除非另行指明,每个元素自动位于这个名称空间。

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"是XAML名称空间。包含各种XAML使用特性,这些特性可影响文档的解释方式。该名称空间被映射为前缀x,意味着可通过在元素名称之前放置名称空间前缀x来使用该名称空间。

    namespace WpfLearn
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }


    Visual Studio自动创建可以放置事件处理代码的部分类,InitializeComponent()当创建类的一个实例时,默认构造函数调用InitializeComponent()方法,此方法不可删除,为窗口类添加另一个构造函数,也要确保调用此方法。InitializeComponent()方法的所有工作就是调用System.Windows.Application类的LoadComponent()方法。LoadComponent()方法从程序集中提取BAML(编译过的XAML),并用它来构建用户界面。当解析BAML时,它会创建每个控件对象,设置其属性,并关联所有事件处理程序。

    命名元素
    在代码隐藏类中,希望通过代码操作控件。如需要读取或修改属性,或自由地关联以及断开事件处理程序。若要实现,控件必须包含XAML Name特性。
    可在XAML文档中手动增加关联名称(使用x:前缀)
        <Grid x:Name="grid1">
    
        </Grid>


    或者在设计器中Properties中设置其Name属性。
    代码中就可以直接使用grid1:MessageBox.Show(string.Format("The grid is {0}", grid1.ActualHeight));
    RuntimeNameProperty特性指示哪个属性的值将作为该类型的实例的名称。FrameworkElement类使用RuntimeNameProperty特性进行了修饰。

    传统的Windows窗体应用程序中,每个控件都有名字。WPF中,没有此要求,当不需要元素名称时通常会省略。
    Grid控件是WPF中最常见的用于安排布局的工具

    任何XAML标签集合都可以用一系列执行相同任务的代码语句代替。
    标记扩展
    使用标记扩展的情况:1、希望将属性值设置为一个已经存在的对象,或者可能希望通过将一个属性绑定到另一个控件来动态地设置属性值。
    <x:Static Member="SystemColors.ActiveCaptionBrush">
                    </x:Static>


    附加属性
    是可用于多个控件但在另一个类中定义的属性。在WPF中,附加属性常用于控件布局。
    事件
    XAML用来修改界面,而非整个用户界面手动编写XAML。

    WPF布局原则

    几个原则
    1、不应显式设定元素(如控件)的尺寸;可以设置最大和最小尺寸来限制。
    2、不应使用屏幕坐标指定元素的位置。需要在元素之间添加空白空间,可使用margin属性。
    3、布局容器的子元素“共享”可用的空间;
    4、可嵌套的布局容器。典型的使用Grid面板为开始,Grid面板是WPF中功能最强大的容器。
    滚动是由特定的内容控件ScrollViewer提供。
    background属性是用于为面板背景着色的画刷,如果想接收鼠标事件,就必须将该属性设置为非空值(如果想接收鼠标事件,又不希望显示固定颜色的背景,将背景色设置为透明即可。

    Border控件
    其属性用来设置边框的背景、颜色,大小和宽度,圆角等。
    WrapPanel面板
    控制界面的一小部分布局。
    DockPanel
    沿着外边沿拉伸所包含的控件。




    ..


    .....







    ..

    展开全文
  • VS Xaml WPF智能提示消失 解决方法

    千次阅读 2008-09-12 11:41:00
    如果VS2008 WPF Designer的Intellisense在安装了最新的Windows SDK/MSDN之后不工作了 最近这些日子,很多程序员反映,在安装了最新的Windows SDK for Windows Server 2008 and .NET Framework 3.5之后,VS2008 WPF ...
    如果VS2008 WPF Designer的Intellisense在安装了最新的Windows SDK/MSDN之后不工作了 

    最近这些日子,很多程序员反映,在安装了最新的Windows SDK for Windows Server 2008 and .NET Framework 3.5之后,VS2008 WPF Designer的Intellisense就不再工作了。他们不得不重新安装或者修复VS2008。 

    这往往是因为一个Registry Key的值被SDK的安装程序错误地删除了。 

    请检查HKEY_CLASSES_ROOT/CLSID/{73B7DC00-F498-4ABD-AB79-D07AFD52F395}/InProcServer32下,(Default)的值是否为空。如果是,你需要将其更新为TextMgrP.dll的完整路径。TextMgrP是Visual Studio Text Manager Proxy。 

    在我的系统上,该文件在C:/Program Files/Common Files/Microsoft Shared/MSENV/TextMgrP.dll。更新之后,Intellisense就又可以工作了。 

    如果您不想自己修改注册表值,也可以通过VS安装程序的修复功能,恢复原先正确的状态。 

    (而安装程序的问题,也会在近期解决。) 
    展开全文
  • XAML C# WPF

    2013-01-07 15:24:29
    XAML定义  XAML是一种相对简单、通用的声明式编程语言,它适合于构建和初始化.NET对象。  XAML仅仅是一种使用.NET API的方式,把它与HTML、可伸缩向量图形...因此,如果在没有WPF这样的框架的基础上讨论XAML,就如

    XAML定义

      XAML是一种相对简单、通用的声明式编程语言,它适合于构建和初始化.NET对象。

      XAML仅仅是一种使用.NET API的方式,把它与HTML、可伸缩向量图形(SVG)或其他特定领域的格式或语言作比较是完全错误的。XAML由一些规则(告诉解析器和编译器如何处理XML)和一些关键字组成,但它自己没有任何有意义的元素。因此,如果在没有WPF这样的框架的基础上讨论XAML,就如同在没有.NET Framework的基础上讨论C#一样。

      XAML在WPF中扮演的角色通常是令人困惑的,因此第一件要搞清楚的事情是WPF和XAML可以独立使用,它们并不是互相依赖的。虽然XAML最初是为WPF而设计,但它也可以应用于其他技术(如WF)。由于XAML的通用性,实际上可以把它应用于任何.NET技术。然而,是否在使用WPF时使用XAML是可选的,每一件XAML能做的事情完全可以由任何一种你喜欢的.NET语言来实现(但反过来则不行)。但是,由于XAML的诸多好处,很少会看到现实世界中使用WPF却不使用XAML的情况。

    元素和特性

      XAML规范定义了一些规则,用于把.NET命名空间、类型、属性和事件映射为XML命名空间、元素和特性。以下面为例,它定义了一个WPF按钮,跟另一段与之功能一致的C#代码比较一下:

      XAML:

    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Content="OK" Click="button_Click"/>

      C#:

    System.Windows.Controls.Button b = new System.Window.Controls.Button();
    b.Content = "OK";
    b.Click += new System.Windows.RoutedEventHandler(button_Click);

      虽然这两段代码功能是相同的,但如果去除掉XAML中的Click特性,你可以很快地在IE浏览器中查看XAML,还会看到一个活生生的按钮放在浏览器窗口中。而C#代码则必须要额外的代码编译方可使用。

      在XAML中定义一个XML元素(叫作对象元素)与在.NET中实例化一个对应的对象(总是使用默认的构造函数)是等价的。设置对象元素的一个特性(attribute),与设置一个同名属性(property attribute,称为属性特性)或者为一个同名事件设置一个事件处理程序(也称为事件特性),也是等价的。

    生成和事件处理的顺序

      在运行时(run-time)模式下,为任何一个XAML声明的对象设置属性之前,总要添加一些事件处理程序,这样就可以让某个事件在属性被设置时被触发,而不用担心XAML使用特性的顺序。

      至于多个属性集或添加多个事件处理程序,它们总会遵照一定顺序,即属性特性和事件属性是在对象元素中指定的。这一排序方式不会在实际应用中产生影响,因为.NET设计指南指出:类应该允许以任何顺序设置属性,添加事件处理程序也是如此。

    命名空间

      比较上述XAML代码示例和相应的C#代码示例,最神秘的地方在于XAML命名空间(http://schemas.microsoft.com/winfx/2006/xaml/presentation)是如何被映射到.NET命名空间(System.Windows.Controls)上的。该映射及其他WPF命名空间的映射是在WPF程序集中硬编码完成的,里面有好几个Xmlns-DefinitionAttribute自定义特性的实例。(在schemas.microsoft.com这个URL中不存在网页,这仅仅是一个人为设定的字符串,就像其他命名空间一样。)

      XAML文件的根对象元素属性指定至少一个XML命名空间,用于验证自己和子元素。你可以(在根元素或子元素上)声明额外的XML命名空间,但每一个命名空间下的标识符都必须有一个唯一的前缀。例如,WPF的XAML文件都会使用第二个命名空间加上前缀x(记作xmlns:x而不仅仅是xmlns):

      xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

      这是XAML语言命名空间,用于映射System.Windows.Markup命名空间中的类型,而且它也定义了XAML编译器或解析器中的一些特殊的指令。这些指令通常是作为XAML元素的特性出现的,因此,它们看上去像宿主元素的属性,但实际上并不是如此。

      我们把http://schemas.microfost.com/winfx/2006/xaml/presentation作为默认(主要)命名空间,把http://schemas.microsoft.com/winfx/2006-/xaml作为次要命名空间。次要命名空间的前缀是x,这仅仅是一个规则,就像C#文件要以using System;指令开始一样。你可以改写原来那个XAML文件,含义是相同的:

    <WpfNamespace:Button xmlns:WpfNamespace="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Content="OK"/>

      当然,从可读性来讲,在使用这些常见的命名空间的时候不需要前缀(即原始的XML命名空间),其他一些命名空间则使用一个短前缀。

    属性元素

      富创建是WPF的亮点之一,我们可以用Button来演示。你可以把任意内容放在Button里面,不仅限于文本,如下所示(在Button中嵌入了一个简单的方形来做一个VCR的停止按钮):

    System.Windows.Controls.Button b = new System.Windows.Controls.Button();
    System.Windows.Shapes.Rectangle r = new System.Windows.Shapes.Rectangle();
    r.Width = 40;
    r.Height = 40;
    r.Fill = System.Windows.Media.Brushes.Black;
    b.Content = r;  //将按钮中的内容设置为方格

      Button的Content属性是System.Object类型的,因此它很容易被设置到40*40的Rectangle对象。但如何才能在XAML中用属性特性语法做相同的事呢?你该为Content属性设置哪种字串才能完成C#中声明的Rectangle功能呢?没有这样的字串,但XAML提供了一种替代的语法来设置复杂的属性值,即属性元素。如下所示:

    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Button.Content>
        <Rectangle Height="40" Width="40" Fill="Black"/>
    </Button.Content>
    </Button>

      Content属性被设置为一个XML元素而不是XML特性,Button.Content中的句点用于区分对象元素(object element)与属性元素(property element)。它们总会以“类型名,属性名TypeName.PropertyName”的形式出现,总会包含在“类型名”对象元素中,但它们没有属于自己的特性。

      属性元素语法也可以用于简单的属性值。下面的Button使用特性设置了两个属性,它们是Content和Background:

    <Button xmlns="http://schema.microsoft.com/winfx/2006/xaml/presentation" Content="OK" Background="White"/>

      这等同于使用元素设置该Button的两个相同的属性:

    复制代码
    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Button.Content>
         OK 
    </Button.Content>
    <Button.Background>
         White
    </Button.Background>
    </Button>
    复制代码

      当然,在任何可以使用特性的地方使用特性更为便捷。

    类型转换器

      上例XAML文件中的“white”是如何与C#中的System.Windows.Media.Brushes.White等价的呢?这个示例提供了一些如何使用字符串设置XAML属性的细节,这些属性的类型即不是System.String,也不是System.Object。在这种情况下,XAML解析器或编译器必须寻找一个类型转换器,该转换器知道如何将一个字符串表达式转换为一种想要的数据类型。WPF提供了许多常用数据类型的类型转换器,如Brush、Color、FontWeight、Point等,它们都派生自Type-Converter的类(如BrushConverter、ColorConverter等),你也可以为自定义的数据类型写类型转换器。与XAML语言不同,类型转换器通常支持不区分大小写的字符串。

      如果没有Brush类型转换器,你就必须使用属性元素语法来设置XAML中的Background属性,如下所示:

    复制代码
    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Content="OK">
    <Button.Background>
        <SolidColorBrush>
        <SolidColorBrush.Color>
            <Color A="255" R="255" G="255" B="255"/>
        </SolidColorBrush.Color>
        </SolidColorBrush>
    </Button.Background>
    </Button>
    复制代码

      由上可见,类型转换器不仅增强了XAML的可读性,也使一些本来不能被表达的概念得以表达。

      下面的代码更精确地表达了运行时获取和执行适合Brush的类型转换器的过程:

    System.Windows.Controls.Button b = new System.Windows.Controls.Button();
    b.Content = "OK";
    b.Background = (Brush)System.ComponentModel.TypeDescriptor.GetConverter(typeof(Brush)).ConvertFromInvariantString("White");

    标记扩展

      标记扩展就像类型转换器一样,可用于扩展XAML的表达能力。它们都可以在运行时计算字符串特性的值,并生成一个合适的基于字符串的对象。WPF有好几个内建的标记扩展,你会发现它们都派生自本书最前面的内封中的MarkupExtension。

      与类型转换器不同的是,标记扩展是通过XAML的显式的、一致的语法调用的,因此,标记扩展是最好的扩展XAML的方法。

      只要特性值由花括号括起来,XAML编译器或解析器就会把它认作一个标记扩展值而不是一个普通的字符串。下面的按钮使用了3个不同的标记扩展类型,其中分别用到了3个不同的特性:

    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Background="{x:Null}"
    Height="{x:Static SystemParameters.IconHeight}"
    Content="{Binding Path=Height, RelativeSource={RelativeSource Self}}"/>

      每个花括号中的第一个识别符是标记扩展类的名称。按照惯例,这样的类都以Extension后缀结尾,但在XAML中使用它时,可以不用该后缀。在上面例子中,NullExtension(即x:Null)和StaticExtension(即x:Static)是System.Windows.Markup命名空间的类,因此必须使用前缀x来定位它们。Binding(没有Extension后缀)是在System.Windows.Data命名空间下的,因此在默认的XML命名空间下就可以找到它。

      如果标记扩展支持,可使用逗号分隔的参数来指定它的值。

      定位参数(如本例中的SystemParameters.IconHeight)被作为字符串参数传入扩展类的相应构造函数中。命名参数(如本例中的Path和RelativeSource)可用来在已构造好的扩展对象上设置相应名字的属性。这些属性的值可以是标记扩展值自己,也可以是文本值,它们可通过普通的类型转换过程。你可能注意到设计和使用标记扩展与设计和使用自定义特性很相似,这是被有意设计的。

      在本例中,NullExtension允许设置Background笔刷为null。StaticExtension允许使用静态属性、字段、常量和枚举值,而不使用XAML写的硬编码字面值。在这个例子中,Button的高度是遵循操作系统当前的图标高度设置的,这一设置可通过System.Windows.SystemParameters类的IconHeight静态字段获得。Binding可以把Content设置为与它的Height属性相同的值。

      如果你需要设置一个属性特性值为字面字符串(以左花括号开始),就必须将其转义,我们可通过在其前面增加一对空花括号来实现,如:

    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    Content="{}{This is not a markup extension!}"/>

      此外,也可以使用属性元素语法,因为花括号在上下文中不会有特殊的意义:

    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
        {This is not a markup extension}
    </Button>

      因为标记扩展是有默认构造函数的类,它们可以与属性元素语法一起使用,如下例:

    复制代码
    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Button.Background>
        <x:Null/>
    </Button.Background>
    <Button.Height>
        <x:Static Member="SystemParameters.IconHeight"/>
    </Button.Height>
    <Button.Content>
        <Binding Path="Height">
        <Binding.RelativeSource>
            <RelativeSource Mode="Self"/>
        </Binding.RelativeSource>
        </Binding>
    </Button.Content>
    </Button>
    复制代码

      该转换之所以可以执行是因为这些标记扩展都有与形参化的构造函数的实参(使用属性特性语法的定位实参)对应的属性。例如,StaticExtension有一个Member属性与之前传入到开参化构造函数中的实参意思是一样的,RelativeSource有一个对应于构造函数实参的Mode属性。

      由于标记扩展完成的实际工作对于每个扩展都是不同的。如下面的C#代码与使用NullExtension、StaticExtension和Binding的基于XAML表示的按钮是一个意思:

    复制代码
    System.Windows.Controls.Button b = new System.Windows.Controls.Button();
    //设置Background
    b.Background = null;
    //设置Height
    b.Height = System.Windows.SystemParameters.IconHeight;
    //设置Content
    System.Windows.Data.Binding binding = new System.Windows.Data.Binding();
    binding.Path = new System.Windows.PropertyPath("Height");
    binding.RelativeSource = System.Windows.Data.RelativeSource.Self;
    b.SetBinding(System.Windows.Controls.Button.ContentProperty, binding);
    复制代码

      尽管如此,这里的代码与XAML解析器或编译器使用的机制是不同的,解析器和编译器是依靠每个标记扩展在运行时设置合适的值(本质上是通过调用每个类的ProvideValue方法来实现的)。与这一机制完全对应的过程式代码通常很复杂。

    对象元素的子元素

      XAML文件就像所有的XML文件一样,必须有一个单独的根对象元素。对象元素是可以支持子对象元素的。一个对象元素可以有3种类型的子元素:一个内容属性值,集合项,或一个能够通过类型转换到它的父元素的值。

    内容属性

      大多数WPF类(通过定制特性)指定了一个属性,该属性可以被设置为XML元素中的任何内容。这个属性叫作内容属性,它确实是一个让XAML呈现变得更轻便简单的捷径。从某种意义上讲,这些内容属性有点像VB中的默认属性。Button中的Content属性就是这样指定的,如:

    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Content="OK"/>

      可以被重写为:

    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    OK
    </Button>

      还有更复杂的方式:

    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Button.Content>
        <Rectangle Height="40" Width="40" Fill="Black"/>
    </Button.Content>
    </Button>

      可以被重写为:

    <Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
        <Rectangle Height="40" Width="40" Fill="Black"/>
    </Button>

    集合项

      XAML允许将项添加到支持索引的两种类型的集合中:List和Dictionary。

    List

      List是实现了System.Collection.IList接口的集合,如System.Collections.ArrayList和许多WPF定义的集合类都是List。如,下面的XAML向ListBox添加了两个项,它的Items属性是实现了IList的ItemCollection类型:

    <ListBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> 
    <ListBox.Items>
         <ListBoxItem Content="Item 1"/>
         <ListBoxItem Content="Item 2"/> 
    </ListBox.Items> 
    </ListBox>

      因为Items是ListBox的内容属性,可以进一步简化:

    <ListBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
        <ListBoxItem Content="Item 1"/>
        <ListBoxItem Content="Item 2"/>
    </ListBox>

    Dictionary

      System.Windows.ResourceDictionary是WPF中的一个常用的集合类型,它实现了System.Collections.IDictionary接口,能够支持在过程式代码中添加、移除枚举键/值对。下面的XAML添加了两个Color对象到一个ResourceDictionary中。

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Color x:Key="1" A="255" R="255" G="255" B="255"/>
        <Color x:Key="2" A="0" R="0" G="0" B="0"/>
    </ResourceDictionary>

      注意,在带有x:Key的XAML中指定的值总是被作为字符串处理的,除非使用标记扩展,但不会尝试使用类型转换。

      XAML是设计用来与.NET类型系统一起工作的,你可以在其中使用任何类型的.NET对象,也可以使用自己定义的对象。但对象必须以“友好声明”的方式进行设计。如果一个类没有默认构造函数,也没有提供有用的实例属性,那么它在XAML中是无法直接使用的。

      WPF程序集都被加上了XmlnsDefinitionAttribute属性,这样可以将.NET命名空间映射为XAML文件中的XML命名空间,但对于那个不是专门为XAML设计的程序集又该如何处理呢?它们的类型仍然可以使用,只需要一个特殊的指令作为XML命名空间就可以了。如下例:

    System.Collections.Hashtable h = new System.Collections.Hashtable();
    h.Add("key1", 1);
    h.Add("key2", 2);

      以上代码在XAML中表示为:

    <collections:Hashtable xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <sys:Int32 x:Key="key1">1</sys:Int32>
        <sys:Int32 x:Key="key2">2</sys:Int32>
    </collections:Hashtable>

      clr-namespace标记允许直接在XAML中放入一个.NET命名空间。

      为了避免混淆,在转换子元素时,任何一个有效的XAML解析器或编译器必须遵循下面的规则:

    1. 如果该类型实现了IList接口,就为每个子元素调用IList.Add。
    2. 否则,如果该类型实现了IDictionary,就为每个子元素调用IDictionary.Add,在该值的键和元素中使用x:Key特性值。
    3. 否则,如果父元素支持内容属性(由System.Windows.Markup.ContentPropertyAttribute表示),而且子元素的类型与该内容属性是兼容的,就把子元素作为它的值。
    4. 否则,如果子对象是普通文本,且有类型转换器将子对象转换为父类型(没有在父元素上设置属性),则把子元素作为类型转换器的输入,将输出作为父对象的实例。
    5. 其他情况下则抛出错误。

    编译:将XAML与过程式代码混合使用

      大多数WPF应用程序是XAML与过程式代码的混合体。

    在运行时加载和解析XAML

      WPF的运行时XAML解析器公开为两个类,它们都位于System.Windows.Markup命名空间中:XamlReader和XamlWriter。XamlReader包含了一些对静态Load方法的重载,而XamlWriter包含了一些对静态Save方法的重载。因此,用任何一种.NET语言写的程序都可以在运行时依赖XAML,而不用程序员付出太多努力。

    XamlReader

      XamlReader.Load方法的设置将解析XAML,创建合适的.NET对象,然后返回一个根元素的实例。因此,如果在当前目录下有一个XAML文件叫作MyWindow-.xaml,它包含了一个Window对象作为根结点,那么可以使用下面的代码来加载和获得Window对象。

    Window window = null;
    using(FileStream fs = new FileStream("MyWindow.xaml", FileMode.Open, FileAccess.Read))
    {
        //获得根元素,该元素是一个Window对象
        Window = (Window)XamlReader.Load(fs);
    }

      在Load返回之后,整个XAML文件的对象层级将在内存中被实例化,因此就不再需要XAML文件了。退出using代码块后,FileSteam将被立即关闭。由于可向XamlReader传入一个任意的Stream(或使用另一个重载来传入System.Xml.XmlReader对象),所以有许多可选择的方式来获得XAML的内容。

      XamlReader也定义了LoadAsync实例方法用于异步加载和解析XAML内容。在加载大文件或网络文件时,可使用LoadAsync保持用户界面处于响应状态。CancelAsync方法用于停止处理,LoadCompleted事件可让我们知道处理何时完成。

      既然已有一个根元素的实例存在,就可利用适当的内容属性或集合属性来获得子元素。下面的代码假设Window有一个类行为StackPanel的子元素,Stack-Panel的第5个子对象是一个OK Button。

    复制代码
    Window window = null;
    using(FileStream fs = new FileStream("MyWindow.xaml"), FileMode.Open, FileAccess.Read))
    {
        //获得根元素,该元素是一个Window对象
        window = (Window)XamlReader.Load(fs);
    }
    //通过(硬编码知识)遍历子元素获取OK按钮
    StackPanel panel = (StackPanel)window.Content;
    Button okButton = (Button)panel.Children[4];
    复制代码

      有了这个Button的引用,就可以做任何想做的事:设置额外的属性,添加事件处理程序,或执行一些无法用XAML完成的动作。

      但使用硬编码索引和其他关于用户界面结构假设的代码并不能让人满意。XAML支持元素命名,这样就可以从过程式代码中找到这些元素并放心地使用它们。

    命名XAML元素

      XAML语言命名空间有一个Name关键字,它是用来给元素命名的。示例如下:

    <Button x:Name="okButton">OK</Button>

      上例代码可改如下:

    复制代码
    Window window = null;
    using(FileStream fs = new FileStream("MyWindow.xaml"), FileMode.Open, FileAccess.Read)) 
    {
         //获得根元素,该元素是一个Window对象
        window = (Window)XamlReader.Load(fs); 
    } 
    //通过按钮的名称获得OK按钮Button 
    okButton = (Button)window.FindName("okButton");
    复制代码

      FindName并不仅仅在Window类中存在,在FrameworkElement、FrameworkContentElement及许多重要的WPF类的基类中也有FindName的定义。

    编译XAML

      XAML编译包括三项事件:

    1. 将一个XAML文件转换为一种特殊的二进制格式。
    2. 将转换好的内容作为二进制资源嵌入到正在被创建的程序集中。
    3. 执行链接操作,将XAML和过程式代码自动连接起来。

      如果你不在乎将XAML文件和过程式代码融合,那么只需把它添加到VS的WPF项目中来,并用界面中的Build动作来完成编译即可。但如果要编译一个XAML文件并将它与过程式代码混合,第一步要做的就是为XAML文件的根元素指定一个子类,可以用XAML语言命名空间中的Class关键字来完成。例如:

    <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="MyNamespace.MyWindow">
    ...
    </Window>

      在一个独立的源文件中(但是在同一个项目中),可以一个子类,并添加任何想添加的成员:

    复制代码
    namespace MyNamespace
    {
        partial class MyWindow : Window
        {
            public MyWindow
            {
                //一定要调用,这样才能加载XAML定义的内容
                InitializeComponent();
                ...
            }
            Any other members can go here...
        }
    }
    复制代码

      通常我们把这样的文件叫作代码隐藏文件。如果你引用XAML中的任何一个事件处理程序(通过事件特性,如Button的Click特性),这里就是我们定义这些事件处理程序的地方。

      当在VS中创建一个基于WPF的C#或VB项目,或当使用“Add New Item...”来添加某WPF项目时,VS会自动创建一个XAML文件,并把x:Class作为根元素,同时创建一个具有部分类定义的代码隐藏源文件,最后把两者连接起来,这样代码构建(build)才能顺利进行。

    BAML

      BAML是Binary Application Markup Language的缩写,意思是二进制应用程序标记语言,它其实是被解析、标记化,最后转换为二进制形式的XAML。虽然大块的XAML代码可以被表示为过程式代码,但XAML到BAML的编译过程不会生成过程源代码。因此,BAML不像MSIL,它是一个压缩的声明格式,比加载和解析普通的XAML文件快,且比普通XAML文件要小。BAML仅仅是XAML编译过程的详细实现,没有任何直接公开的方法,在未来可能会被一些其他东西所取代。

    生成的源代码

      x:Class只能在要编译的XAML文件中使用。但在没有x:Class的情况下,编译XAML文件也是没有问题的。这意味着没有对应的代码隐藏文件,因此不能使用任何需要过程式代码才能实现的特性。

      每个生成的源文件中包含了一个由根对象元素中的x:Class指定的类的部分类定义。XAML文件中的每个已命名的元素在该部分类中都有一个成员(默认是私有的),这些成员的名称就是元素名称。其中还有一个InitializeComponent方法用于完成一大堆烦人的工作。

    BAML可以反编译为XAML吗?

      可以,无论怎么声明,任何一个公司的.NET类实例都可以被序列化为XAML。第一个步骤是获取一个实例,这个实例是用来作为根对象的。如果你还没有这个对象,可以调用静态的System.Windows.Application.LoadComponent方法,如下所示:

    System.Uri uri = new System.Uri("MyWindow.xaml", System.UriKind.Relative);
    Window window = (Window)Application.LoadComponent(uri);

      由URI指定的名称并不要求物理上存在一个独立的xaml文件。当指定了一个合适的URI后,LoadComponent可以自动获得作为资源嵌入的BAML。实际上,VS自动生成的InitializeComponent方法就是调用Application.LoadComponent来加载嵌入的BAML。

      获得根元素的实例后,可以使用System.Windows.Markup.XamlWrite类来获得根元素的XAML表示。XamlWriter包含了5个静态Save方法的重载,是最简单的返回一个适当XAML字符串的方法,通过传入一个对象实例来实现。如:

    string xaml = XamlWriter.Save(window);

    XAML关键字

      XAML语言的命名空间(http://schemas.microsoft.com/winfx/2006/xaml)定义了一批XAML编译器或解析器必须特殊处理的关键字。它们主要控制元素如何被提供给过程式代码,但即使没有过程式代码,有一些关键字还是有用的。如Key、Name、Class、Subclass和Code。

    展开全文
  • word文档 提供目录 WPF统一了Windows创建、显示、操作文档、媒体和用户...从WPF的体系结构开始,向您全面介绍WPF开发所需的基础知识、XAML语法、控件开发和数据通信,最后向您展示WPF在图形和多媒体方面的强大威力。
  • XAML and WPF

    2007-09-27 15:59:00
    XAML and WPF XAML-Extensible Application Markup LanguageWPF-Windows Presentation FoundationExtensible Application Markup Language (XAML) is a markup language for declarative application programming....
    XAML and WPF 
    XAML-Extensible Application Markup Language
    WPF-Windows Presentation Foundation
    Extensible Application Markup Language (XAML) is a markup language for declarative application programming. Windows Presentation Foundation (WPF) implements a Extensible Application Markup Language (XAML) loader and provides Extensible Application Markup Language (XAML) language support for Windows Presentation Foundation (WPF) types such that you can create the majority of your application UI in Extensible Application Markup Language (XAML) markup.
    In This Section
    XAML Overview

    XAML Syntax Terminology

    Code-Behind and XAML

    XAML and Custom Classes

    Markup Extensions and XAML

    XAML Namespaces and Namespace Mapping

    WPF Namescopes

    Inline Styles and Templates

    Whitespace Processing in XAML

    TypeConverters and XAML

    XAML Namespace (x:) Language Features

    WPF Namespace XAML Extensions

    Markup Compatibility (mc:) Language Features

    Related Sections
    WPF Architecture

    Base Elements

    Element Tree and Serialization

    Properties

    Events

    Input and Commands

    Resources

    Styling and Templating

    WPF Fundamentals: Content Models

    Threading Model

    XAML Overview
    This topic describes the features of the Extensible Application Markup Language (XAML) language and demonstrates how you can use XAML to write Windows Presentation Foundation (WPF) applications. This topic specifically describes XAML as implemented by Windows Presentation Foundation (WPF). XAML itself is a larger language concept than Windows Presentation Foundation (WPF).
    This topic contains the following sections.
    XAML is a Declarative Language With Flow Control Support

    XAML Object Elements

    Setting Properties

    Markup Extensions

    Typeconverter-Enabled Attribute Values

    Collection Types and XAML Collection Properties

    XAML Content Properties

    Case and Whitespace in XAML

    More about XAML Syntax

    XAML Root Elements and xmlns

    Events and XAML Code-Behind

    x:Name

    Attached Properties and Attached Events

    Base Classes and XAML

    XAML Security

    What's Next

    Related Topics
    XAML is a Declarative Language With Flow Control Support
    XAML simplifies creating a UI for the .NET Framework 3.0 programming model. You can create visible UI elements in the declarative XAML markup, and then separate the UI definition from the run-time logic by using code-behind files, joined to the markup through partial class definitions. The ability to mix code with markup in XAML is important because XML by itself is declarative, and does not really suggest a model for flow control. An XML based declarative language is very intuitive for creating interfaces ranging from prototype to production, especially for people with a background in web design and technologies. Unlike most other markup languages, XAML directly represents the instantiation of managed objects. This general design principle enables simplified code and debugging access for objects that are created in XAML.
    XAML files are XML files that generally have the .xaml extension.
    The following XAML example shows how little markup is necessary to create a button as part of a UI. The created button has default visual presentation through theme styles, and default behaviors through its class design.

    XAML
    程序代码 程序代码
    <StackPanel>
      <Button Content="Click Me"/>
    </StackPanel>


    XAML Object Elements
    XAML has a set of rules that map object elements into classes or structures, attributes into properties or events, and XML namespaces to CLR namespaces. XAML elements map to Microsoft .NET types as defined in referenced assemblies, and the attributes map to members of those types.

    The preceding example specified two object elements: <StackPanel> (with a closing tag), and <Button /> (which also had several attributes; attributes are discussed in an upcoming section). The strings StackPanel and Button each map to the name of a class that is defined by WPF and is part of the WPF assemblies. When you specify an object element tag, you create an instruction for the XAML loader to create a new instance of the named class when your XAML page is either compiled or interpreted. Each instance is created by calling the default constructor of the underlying class or struct and storing the result. To be usable as an object element in XAML, the class must expose a public default (parameterless) constructor.

    Setting Properties
    Properties in XAML are set by setting properties on an object element, using a variety of possible syntaxes. Which syntaxes can be used for a given property will vary, based on the characteristics of the property that you are setting.

    By setting values of properties, you add features or characteristics to object elements. The initial state of the underlying object instance for an object element is based on the default constructor behavior. Typically, you want something other than a completely default class instance.

    Attribute Syntax
    In XAML, properties can often be expressed as attributes. Attribute syntax is the most streamlined property setting syntax and will be the most intuitive syntax to use for developers that have used markup languages in the past. For example, the following markup creates a button that has red text and a blue background, as well as display text specified as Content.

    XAML
    程序代码 程序代码
    <Button Background="Blue" Foreground="Red" Content="This is a button"/>


    Property Element Syntax
    For some properties of an object element, attribute syntax is not possible, because the object or information necessary to provide the property value cannot be adequately expressed as a simple string. For these cases, a different syntax known as property element syntax can be used. Property element syntax sets the referenced property of the containing element with a new instance of the type that the property takes as its value (with the value-setting instance typically specified as another object element). The syntax for a property element is <TypeName.Property>. For properties where both attribute and property element syntax are supported, the two syntaxes generally have the same result, although subleties such as whitespace handling can vary slightly between syntaxes. If an attribute syntax is possible, using the attribute syntax is typically more convenient and enables a more compact markup, but that is just a matter of style, not a technical limitation. The following example shows the same properties being set as in the previous attribute syntax example, but this time by using property element syntax for all properties of the Button.

    XAML
    程序代码 程序代码
    <Button>
      <Button.Background>
        <SolidColorBrush Color="Blue"/>
      </Button.Background>
      <Button.Foreground>
        <SolidColorBrush Color="Red"/>
      </Button.Foreground>
      <Button.Content>
        This is a button
      </Button.Content>
    </Button>


    Properties and Class Inheritance
    Properties as they appear as XAML attributes on a WPF element are often inherited from base classes. For example, in the previous example, the Background property is not an immediately declared property on the Button class if you were to look at the class definition. Instead, Background is inherited from the base Control class.

    Markup Extensions
    When properties take a reference type value, these properties will often require either property element syntax (which always creates a new instance), or an object reference through a markup extension. A markup extension usage can potentially return an existing instance, and thus can be more versatile or might incur less object overhead. Markup extensions are a XAML concept. In attribute syntax, curly braces ({ and }) indicate a markup extension usage. This usage directs the XAML loader to escape from the general treatment of attribute values as either a literal string or a directly string-convertible value. The attribute value should instead be provided by the logic within the backing class for the relevant markup extension. The most commonly used markup extensions for application programming are Binding Markup Extension, used for data binding e­xpressions, and the resource references StaticResource Markup Extension and DynamicResource Markup Extension. By using markup extensions, you can use attribute syntax to provide reference values for properties even if that property does not support an attribute syntax for direct object instantiation.

    For instance, the following example sets the value of the Style property using attribute syntax. The Style property takes an instance of the Style class, a by-reference type that by default could not be specified within an attribute syntax string. But in this case, the attribute references a particular markup extension, StaticResource. When that markup extension is processed, it returns a reference to a style that was previously instantiated as a keyed resource in a resource dictionary.

    XAML
    程序代码 程序代码
    <Page.Resources>
      <SolidColorBrush x:Key="MyBrush" Color="Gold"/>
      <Style TargetType="Border" x:Key="PageBackground">
        <Setter Property="Background" Value="Blue"/>
      </Style>

      ...

    </Page.Resources>
    <StackPanel>
      <Border Style="{StaticResource PageBackground}">

      ...

      </Border>
    </StackPanel>


    Resources are just one markup extension usage enabled by either WPF or XAML. For a reference listing of markup extensions, see WPF Namespace XAML Extensions or XAML Namespace (x:) Language Features. For more information about markup extensions, see Markup Extensions and XAML.

    Typeconverter-Enabled Attribute Values
    In the Attribute Syntax section, it was stated that the attribute value must be able to be set by a string. The basic, native handling of how strings are converted into other object types or primitive values is based on the String type itself. But many WPF types or members of those types extend the basic string attribute processing behavior, such that instances of more complex object types can be specified as attribute values through a string. At the code level, this processing is accomplished by specifying a CLR type converter that processes the string attribute value. The Thickness structure type, commonly used to indicate measurements of a rectangular area such as a Margin, is an example of a type that has a special typeconverter-enabled attribute syntax exposed for all properties that take that type, to provide ease of use in XAML markup. The following example uses a typeconverter-enabled attribute syntax to provide a value for a Margin:

    XAML
    程序代码 程序代码
    <Button Margin="10,20,10,30" Content="Click me"/>


    The preceding attribute syntax example is equivalent to the following more verbose syntax example, where the Margin is instead set through property element syntax containing a Thickness object element, and four key properties of Thickness are set as attributes on the new instance:

    XAML
    程序代码 程序代码
    <Button Content="Click me">
      <Button.Margin>
        <Thickness Left="10" Top="20" Right="10" Bottom="30"/>
      </Button.Margin>
    </Button>


    Again, whether to use the typeconverter-enabled syntax or a more verbose equivalent syntax is a coding style choice, but the typeconverter-enabled syntax promotes more streamlined markup.

    For more information on how typeconverter-enabled attribute syntax is supported, see TypeConverters and XAML.

    Collection Types and XAML Collection Properties
    XAML specifies a language feature whereby the object element that represents a collection type can be deliberately omitted from markup. When a XAML loader processes a property that takes a collection type, an instance of the appropriate collection type is created implicitly, even if the object element for that collection is not present in the markup. In the SDK reference pages for collection types, this syntax with the deliberate omission of the object element for a collection is occasionally noted in the XAML syntax sections as Implicit Collection Syntax.

    Implicit collection syntax is available for types that implement IList or IDictionary, or for arrays.

    You have already seen an example of an implicit collection syntax without it being called out, in the XAML resources example:

    XAML
    程序代码 程序代码
    <Page.Resources>
      <SolidColorBrush x:Key="MyBrush" Color="Gold"/>
      <Style TargetType="Border" x:Key="PageBackground">
        <Setter Property="Background" Value="Blue"/>
      </Style>

      ...

    </Page.Resources>
    <StackPanel>
      <Border Style="{StaticResource PageBackground}">

      ...

      </Border>
    </StackPanel>


    With the exception of the root element, every object element on a page that is nested as a child element of another element is really an element that is one or both of the following cases: a member of an implicit collection property of its parent element, or an element that specifies the value of the XAML content property for the parent element (XAML content properties will be discussed in an upcoming section). In other words, the relationship of parent elements and child elements in a markup page is really a single object at the root, and every object element beneath the root is either a single instance that provides a property value, or one of the items within a collection. In the case of the resources example, the Resources property takes an object of type ResourceDictionary. The following example is equivalent syntax with the object element for the ResourceDictionary specified explicitly.

    XAML
    程序代码 程序代码
    <Page.Resources>
        <ResourceDictionary>
            <SolidColorBrush x:Key="MyBrush" Color="Gold"/>
            <Style TargetType="Border" x:Key="PageBackground">
              <Setter Property="Background" Value="Blue"/>
            </Style>

        ...

        </ResourceDictionary>
      </Page.Resources>
      <StackPanel>
        <Border Style="{StaticResource PageBackground}">

        ...

        </Border>
      </StackPanel>
    </Page>


    The Resources collection is an example of a collection property that is present on all WPF framework-level elements. Setting this property in XAML requires the property element syntax. Each enclosed object element within the property element becomes an item of the collection (an IDictionary implementation). Although the collection type itself typically does have a property or indexer that contains the items, that property cannot be specified in markup; it is entirely implied. For the ResourceDictionary, that property is the Item indexer.

    For a more complete resource dictionary usage example, see How to: Define and Reference a Resource.

    XAML Content Properties
    XAML specifies a language feature whereby any class that can be used as a XAML object element can designate exactly one of its properties to be the XAML content property for instances of the class. When a XAML loader processes an object element that has a XAML content property, any XML child elements of that object element are processed as if they were contained within an implicit property element tag representing that content property. Within your markup, property element syntax for the XAML content property can be omitted. Any child elements you specify in markup will become the value of the XAML content property.

    You have already seen an example of a XAML content property without it being called out: the very first example in this topic.

    XAML
    程序代码 程序代码
    <StackPanel>
      <Button Content="Click Me"/>
    </StackPanel>


    Here, Button is a child element of StackPanel. This is a streamlined and intuitive markup, that omits two tags for two different reasons.

    Omitted StackPanel.Children property element: StackPanel derives from Panel. Panel defines Panel.Children as its XAML content property. All derived classes of Panel thus have that XAML content property, and the property element for Panel.Children can be omitted.

    Omitted UIElementCollection object element: The Panel.Children property takes the type UIElementCollection, which implements IList. Therefore the UIElementCollection object element tag can be omitted, based on the XAML defined rules for collections. In this case, UIElementCollection actually cannot be instantiated as an object element. You do not even have the option of declaring that collection object explicitly. This is because UIElementCollection does not expose a default constructor. Several other WPF collection types also do not expose constructors for object element usage, because the XAML collection syntax handling still allows them to work in XAML implicitly. That is why the UIElementCollection object element is shown commented in the example; if uncommented, the example would not compile.

    XAML
    程序代码 程序代码
    <StackPanel>
      <StackPanel.Children>
        <!--<UIElementCollection>-->
        <Button>
          <Button.Content>
            Click Me
          </Button.Content>
        </Button>
        <!--</UIElementCollection>-->
      </StackPanel.Children>
    </StackPanel>


    Inner Text and XAML Content Properties
    The StackPanel / Button example has still another variation.

    XAML
    程序代码 程序代码
    <StackPanel>
      <Button>Click Me</Button>
    </StackPanel>


    Notice the change in how the display text for the Button is specified. The Content property was specified in attribute syntax before; this time the display string is the inner text within a Button object element. This syntax works because Content is the XAML content property of the Button base class ContentControl. The string within the element is evaluated based on the property type of the Content property, which is Object. Object does not attempt any string type conversion, therefore the value of the Content property becomes the literal string value. Alternatively, the content within the Button could have been any single Object. Controls such as Button generally define the XAML content property for the class such that the XAML content property can be used for UI and display text, for control compositing, or both.

    The ability to place strings within the element as content to produce markup that resembles other common markup languages is particularly important for the flow document model (for details, see Documents in Windows Presentation Foundation) and for localization (see Globalization for the Windows Presentation Foundation).

    XAML Content Property Values Must Be Contiguous
    The value of a XAML content property must be given either entirely before or entirely after any other property elements on that object element. This is true whether the value of a XAML content property is specified as a string, or as one or more objects. For instance, the following markup does not compile:

    程序代码 程序代码

    <Button>I am a
      <Button.Background>Blue</Button.Background>
    blue button</Button>

    This is illegal essentially because if this syntax were explicit by using property element syntax for the content property, then the content property would be set twice:

    程序代码 程序代码

    <Button>
      <Button.Content>I am a </Button.Content>
      <Button.Background>Blue</Button.Background>
      <Button.Content> blue button</Button.Content>
    </Button>

    A similarly illegal example is if the content property is a collection, and child elements are interspersed with property elements:

    程序代码 程序代码

    <StackPanel>
      <Button>This example</Button>
      <StackPanel.Resources>
        <SolidColorBrush x:Key="BlueBrush" Color="Blue"/>
      </StackPanel.Resources>
      <Button>... is illegal XAML</Button>
    </StackPanel>

    Content Models
    A class might support a usage as a XAML element in terms of the syntax, but that element will only function properly in an application or page when it is placed in an expected position of an overall content model or element tree. For example, a MenuItem should typically only be placed as a child of a MenuBase derived class such as Menu. Content models for specific elements are documented as part of the remarks on the class pages for controls and other WPF classes that can be used as XAML elements. For some controls that have more complex content models, the content model is documented as a separate conceptual topic. See Content Models.

    Case and Whitespace in XAML
    XAML is case sensitive. Object elements, property elements, and attribute names must all be specified by using the proper casing when compared by name to the underlying type in the assembly, or to a member of a type. The values for attributes are not always case sensitive. Case sensitivity for values will depend on the type converter behavior associated with the property that takes the value, or the property value type. For instance, properties that take the Boolean type can take either true or True as equivalent values, but only because the default string type conversion for Boolean already permits these as equivalents.

    XAML loaders and serializers will ignore or drop all nonsignificant whitespace, and will normalize any significant whitespace. This behavior is generally only of consequence when you specify strings within XAML content properties. In simplest terms, XAML converts space, linefeed and tab characters into spaces, and then preserves one space if found at either end of a contiguous string. The full explanation of XAML whitespace handling is not covered in this topic. For details, see Whitespace Processing in XAML.

    More about XAML Syntax
    Implicit collection syntax and XAML content properties are both features of the XAML language that enable omission of certain inferred tags. The goal of these features is to make the parent-child relationships of elements on a page more apparent when authoring or examining the markup.

    For more information about attribute syntax and property element syntax, as well as other terms that are used when describing XAML syntax throughout the SDK documentation, see XAML Syntax Terminology.

    XAML Root Elements and xmlns
    XAML files must have only one root element, in order to be a both well-formed XML file and a valid XAML file. Typically you should choose an element that is part of the application model (for example, Window or Page for a page, ResourceDictionary for an external dictionary, or Application for the application definition root). The following example shows the root element of a typical XAML file for a WPF page, with the root element Page.

    XAML


    The root element also contains the attributes xmlns and xmlns:x. These attributes indicate to the XAML loader which namespaces contain the element definitions. The xmlns attribute specifically indicates the default xmlns namespace. Within the default xmlns namespace, object elements in the markup can be specified without a prefix. For most WPF application scenarios, and for virtually all of the examples given in the WPF sections of the SDK, the default xmlns namespace is mapped to the WPF namespace http://schemas.microsoft.com/winfx/2006/xaml/presentation. The xmlns:x attribute indicates an additional xmlns namespace, which maps the XAML language namespace http://schemas.microsoft.com/winfx/2006/xaml. Required language components defined by the XAML specification are prefixed by x: when referenced in the markup of a file with this mapping. This usage of xmlns to define a scope for usage and mapping is consistent with the XML 1.0 specification. Note that the xmlns attributes are only strictly necessary on the root element of the page or application. xmlns definitions will apply to all child elements of the root (this behavior is again consistent with the XML 1.0 specification for xmlns.) xmlns attributes are also permitted on other elements beneath the root, and would apply to any child elements of the defining element. However, this usage is not typical, because frequent definition or redefinition of xmlns namespaces can result in a markup style that is difficult to read.

    The WPF assemblies are known to contain the WPF namespaces because of configuration that is part of your project build file. Assemblies are also mapped in the targets files. Therefore, mapping the xmlns is all that is necessary in order to reference XAML elements that come from WPF assemblies. For your own custom assemblies, or for assemblies outside of WPF, you can specify the assembly as part of the xmlns mapping. For more information about how xmlns namespaces and the namespaces of the backing code in assemblies are related, see XAML Namespaces and Namespace Mapping.

    The x: Prefix
    In the previous root element example, the prefix x: was used to map the XAML namespace http://schemas.microsoft.com/winfx/2006/xaml. This x: prefix will be used to map the XAML namespace in the templates for projects, in examples, and in documentation throughout this SDK. The x: prefix/XAML namespace contain several programming constructs that you will use quite frequently in your XAML. The following is a listing of the most common x: prefix/XAML namespace programming constructs you will use:

    x:Type: Constructs a Type reference based on a type name. This is used to specify attributes that take Type, such as System.Windows.Style.TargetType.

    x:Key: Sets a unique key for resources in a ResourceDictionary.

    x:Class: Specifies the CLR namespace and class name for the class that provides code-behind for a XAML page.

    x:Static: Enables a value reference to a static value that is not otherwise a XAML settable property.

    There are also more programming constructs in the x: prefix/XAML namespace, which are not as common. For details, see XAML Namespace (x:) Language Features.

    Events and XAML Code-Behind
    Most WPF applications consist of both markup and code-behind. Within a project, the XAML is written as a .xaml file. and a CLR language such as Microsoft Visual Basic .NET or C# is used to write a code-behind file. When a XAML file is compiled, the location of the XAML code-behind file for each XAML page is identified by specifying a namespace and class as the x:Class attribute of the root element of the XAML page.

    In the examples so far, you have seen several buttons, but none of these buttons had any logical behavior associated with them yet. The primary application-level mechanism for adding a behavior for an object element is to use an existing event of the element class, and to write a specific handler for that event that is invoked when that event is raised at runtime. The event name and the name of the handler to use are specified in the markup, whereas the code that implements your handler is defined in the code-behind. 
     
    展开全文
  • XAML@WPF

    2010-03-17 17:41:40
    XAML本身的意义非常广泛。但在目前的程序模式下,主要处理“UI和UI相关处理”已经足够,所以无须再扩充。   Xaml, 全名是eXtensible application markup language,是ms.net框架wpf(/e)的语言集总称。它具有...
  • WPFXAMLWPF核心程序集、App.xaml

    千次阅读 2014-01-14 11:32:54
    一、在XAML中引用命名空间 1、添加对程序集的引用, 2、在根元素的起始标签中写上一句:xmlns:c="clr-namespace:System.Windows.Controls;assembly=PresentationFramework"。  xmlns:c="clr-namespace:命名空间;...
  • WPF XAML概览

    2015-03-06 13:08:06
    微软为了把开发模式从网络开发移植到桌面开发和富媒体网络程序的开发上,微软创造了一种新的开发语言------XAML(读作ZAML),XAML全称Extensible Application MarkUp Language。即可扩展应用程序标记语言。它在做桌面...
  • WPF XAML 系统学习XAML语法

    千次阅读 2015-03-15 18:52:59
    XAML文档的树形结构】    UI在用户眼里面是个平面结构。如下图所示,在用户眼里看来,这个界面就是一个窗体里面平铺了4个文本框和一个按钮的界面。  在传统的Visual C++、Delphi、Visual Basic6.0和...
  • XAML C# WPF 。。

    2015-08-21 11:30:50
    XAML定义  XAML是一种相对简单、通用的声明式编程语言,它适合于构建和初始化.NET对象。  XAML仅仅是一种使用.NET API的方式,把它与HTML、可伸缩向量图形...因此,如果在没有WPF这样的框架的基础上讨论XAM
  • WPF XAML 从零开始认识XAML

    千次阅读 2015-03-09 19:14:24
    剖析最简单的XMAL代码: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml
  • WPFXAML基础

    千次阅读 2014-01-01 21:24:40
    其实我们这里不想讲太多的WPF的概念,因为我们发现不管是MSDN,还是一些介绍WPF的书籍开篇介绍WPF的时候无不介绍了很多WPF的很多新特性,譬如WPF的布局系统,样式,模板等等,我个人觉得对于一个初学者,这些可能会...
  • using System; using System.Windows; using System.Windows.Controls; namespace ConsoleHelloWorld { class Program : Application { [STAThread] static void Main(string[] args)
  • 如果你正在使用WPF、UWP技术进行开发,你一定需要学习Microsoft Blend,在这里你会发现,只需动动鼠标,你就可以迅速开发出又酷、又炫、又华丽应用程序界面,而系统自动为你生成全部的XAML代码。从此告别手工编写...
  • WPF开发教程

    千次阅读 多人点赞 2019-07-02 23:13:20
    ------WPF开发教程 ...2. WPF基础之XAML. 9 3. WPF基础之基元素... 23 4. WPF基础之属性系统... 26 5. WPF基础之路由事件... 33 6. WPF基础之布局系统... 46 7. WPF基础之样式设置和模板化... ...
  • WPF XAML剖析

    2012-01-01 00:48:08
    it seems not bad   ...   and this binding converter http://www.silverlightchina.net/html/study/WPF/2011/0727/9320.html     run ui on
  • 在开始利用XAML开发WPF程序之前,我们最希望的应该是一个强大的WPF开发工具。在本章中,将介绍创建和运行一个XAML程序所必须的软件环境,而后对一个XAML工程的基本结构进行详细的说明,最后就是如何编译和运行一个...
  • wpf xaml 简单例子

    2012-09-08 18:22:24
    wpf xaml 数据binding 简单例子
  • WPF XAML X名称空间详解

    千次阅读 2015-03-18 21:19:49
    X名称空间里面的成员(如X:Name,X:Class)都是写给XAML编译器看的、用来引导XAML编译器将XAML代码编译为CLR代码。 【X名称空间里面到底都有些什么】  x名称空间映射的是:...
  • WPFXAML

    千次阅读 2012-06-11 16:50:14
    WPF(Windows Presentation Foundation)是微软新一代图形系统的,运行在.NET Framework 3.0 架构下,为用户界面、2D/3D 图形、文档和媒体提供了统一的描述和操作方法。基于DirectX9/10技术的WPF不仅带来了前所未有的...
  • eFace 1.0.0 发布:java版本的XAML/WPF

    千次阅读 2007-10-29 15:52:00
    注解:什么是XAML: Extensible Application Markup Language界面描述性语言运行环境: .net 2.0 + WinFX Runtime XAML关注界面编程,分离了界面与后台逻辑分离什么是WPF:WinFX是下一代的Windows API,而WPF将是WinFX...
  • WPF教程 XAML教程

    2013-09-06 08:48:08
    wfp从零开始,xaml从零开始学习,以及mvvm设计模式
  • WPFXAML

    2020-05-07 23:07:42
    什么是XAML XAML是用于实例化.net对象的标记语言。是一种可应用于诸多不同问题领域的技术,但在此是构造wpf界面的。xaml文档的定义用来构造组成窗体的面板按钮以及各种控件。 XAML基础 XAML文档中每一个元素都映射...
  • WPF主题xaml文件

    2013-03-11 15:36:08
    几个外国的WPF主题文件,可以当做资源使用
  • 有极少数的XAML元素存在下面所描述的情况,就是其自身的属性大多数情况下是在其它的元素中进行声明和使用的,该元素本身却很少使用这些属性。这些在其它元素中声明和使用的属性我们称为附加属性。一般来说,附加属性...
  • 使用XAMLWPF项目中承载ArcGIS Engine地图控件开发
  • WPF XAML 画线

    千次阅读 2018-08-13 14:23:53
    &lt;Grid&gt;  &lt;!--直线--&gt;  &lt;Line X1="20" Y1="60" X2="360" Y2="60" Stroke="Green" StrokeThickness="...--虚线--&

空空如也

1 2 3 4 5 ... 20
收藏数 79,357
精华内容 31,742
关键字:

xaml