WPF学习之路(二) XAML

在WPF中引入了XAML语言,主要用于界面设计,业务逻辑则使用C#实现后台代码,将界面设计与业务逻辑分离

XAML是一种声明式语言,类似XMLHTML

示例:

<!--Start Tag-->

<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="300" Height="200">
  <!--Property-->
  <Button.Content>
    Hello XAML
  </Button.Content>
</Button>
<!--End Tag-->

这是一个普通的Button

<DockPanel>
  <Button DockPanel.Dock="Left" Background="AliceBlue" Margin="0,5,0,10" Content="Hello XAML" />
  <Button DockPanel.Dock="Right">
    <Button.Background>
      <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
        <GradientStop Color="Yellow" Offset="0.0" />
        <GradientStop Color="Green" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1" />
      </LinearGradientBrush>
    </Button.Background>
    Hello XAML
  </Button>
</DockPanel>

 在面板(DockPanel)窗口中有两个Button

XAML有两个重要组成:完整的开始/结束标签,即元素;依赖于元素的要素,即属性

命名空间

WPF命名空间 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

XAML至少要指定一个命名空间,为了作用于整个文件,通常放置在根元素中

WPF中有4中元素可以作为根元素:Windows(窗口)、Page(网站页面)、Application(应用程序)、ResourceDictionary(逻辑资源集合)

XAML命名空间 习惯上带有x前缀 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

其他命名空间

 使用系统类

xmlns:s="clr-namespace:System;assembly=mscorlib"

 使用自定义类      自定义类必须有无参构造函数

1.使用本地自定义类

 xmlns:local="clr-namespace:Alex_WPFAPPDemo01"

示例:

public class Book
{
  public string Name { get; set; }
  public double Price { get; set; }

  public Book() { }

  public override string ToString()
  {
    return Name + ": " + Price + "¥";
  }
}

<Window x:Class="Alex_WPFAPPDemo01.MainWindow"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:local="clr-namespace:Alex_WPFAPPDemo01"
     Title="MainWindow" Height="350" Width="525">

  <Grid>
    <Button FontSize="14">
      <local:Book Name="Self-learning WPF" Price="30.0" />
    </Button>
  </Grid>
</Window>

 2.使用外部自定义类

xmlns:customlib="clr-namespace:ThirdDll;assembly=ThirdDll"

To be continue...

原文地址:https://www.cnblogs.com/alex09/p/4428097.html