1.XAML

接触WPF的第一眼就是XAML---XAML是用来描绘界面的。其实不然!

"Actually, XAML has nothing to do with UI. It's merely a declarative way of constructing objects and setting their properties.”

XAML和UI一点关系也没有,它仅仅是一种以声明方式来构建对象,设置对象属性的一种方式而已,和code behind file作用差不多。XAML这种声明方式构建对象的好处是,程序员只管声明自己要什么,至于如何构建则不需要考虑。

XAML对WPF来讲,也不是必须的。我们可以轻松实现一个WPF工程,没有任何XAML。  

XML也不是WPF才有,举个反例如在WF中XAML被用来构建工作流。

2.XAML和编译

"A XAML file is compiled by a XAML compiler that produces a binary version of the XAML, known as BAML. This BAML is stored as a resource inside the assembly and is parsed at runtime in the InitializeComponent call to create the actual objects. The result is bundled with the code behind file (the typical Window class is declared as partial, meaning there may be more source files describing the same class) to produce the final code for that class."

XAML文件首先由XAML编译器编译成二进制的BAML,并以资源的形式存储在程序集中,在运行时由InitializeComponent方法结合后台代码来构建最终的对象。

3.通过XAML来构建后台类对象-Single Object

譬如我们定义一个后台类。如下:

    class Book
{
public string Name { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
public int YearPublished { get; set; } }

我们如何在XAML中访问这个类呢?

1.添加一个XAML映射,code snip如下:

<Window x:Class="CreatingCustomTypeInXaml.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:local="clr-namespace:CreatingCustomTypeInXaml"

如果不在同一个程序集需要加上";assembly=程序集名称"。

2.这样使用

    <Grid>
<Button HorizontalAlignment="Left" Margin="129,82,0,0" VerticalAlignment="Top" Width="" Height="">
<local:Book Name="WPF tutorial" Author="DebugLZQ" YearPublished="" Price="29.99"/>
</Button>
</Grid>

当然,为了使上面的代码正常工作,我们需要为Book类重写一个合适的ToString。

    class Book
{
public string Name { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
public int YearPublished { get; set; } public override string ToString()
     {
      return string.Format("{0} by {1}\npublished {2}",Name,Author,YearPublished);
}
}

程序运行如下:

----

又如,可以在MVVM中可以在View中为Window的DataContent赋值ViewModel(虽不是最好的办法):

<Window x:Class="AsynchronousBindingDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:AsynchronousBindingDemo"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<TextBlock Text="{Binding Text1, IsAsync=True}" FontSize="60" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>

参考DebugLZQ后续博文:

MVVM: Improve MVVM Application Performance Using Framework Features
View and ViewModel Mapping using MEFedMVVM

4.通过XAML来构建后台类对象-Collection Object

上面我们是在XAML中构建简单的Single Object,如果我们需要构建一个数组,该如何做呢?

如,我们有如下一个类:

    public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

现在我们需要用xaml构建这个类的数组。
我们在C#中新增一个类:

    public class PersonList : List<Person>
{ }

上面这个类的目的是用来包装泛型List<Person>,因为泛型对象是无法再xaml中构建的。

其实,我们一般不用List,而是用ObservableCollection。请参考DebugLZQ后续博文:WPF整理-Binding to a Collection
如下使用:

xmlns:local="clr-namespace:CreatingCustomTypeInXaml"
        <ListBox  DisplayMemberPath="Age">
<ListBox.ItemsSource>
<local:PersonList>
<local:Person Name="DebugLZQ1" Age="26"/>
<local:Person Name="DebugLZQ2" Age="26"/>
</local:PersonList>
</ListBox.ItemsSource>
</ListBox>

通常,我们会把XAML构建的对象放到Resource中。如下:

    <Window.Resources>
<local:PersonList x:Key="personList">
<local:Person Name="DebugLZQ1" Age="26"/>
<local:Person Name="DebugLZQ2" Age="26"/>
</local:PersonList>
</Window.Resources>
<ListBox ItemsSource="{StaticResource personList}" DisplayMemberPath="Name"/>

当然,List<int>、List<string>。。。。相同。

运行如下:

附:MainWindow.xaml,MainWindow.xaml.cs

<Window x:Class="CreatingCustomTypeInXaml.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CreatingCustomTypeInXaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:PersonList x:Key="personList">
<local:Person Name="DebugLZQ1" Age="26"/>
<local:Person Name="DebugLZQ2" Age="26"/>
</local:PersonList>
</Window.Resources>
<StackPanel>
<Grid>
<Button HorizontalAlignment="Left" Margin="129,82,0,0" VerticalAlignment="Top" Width="258" Height="107">
<local:Book Name="WPF tutorial" Author="DebugLZQ" YearPublished="2013" Price="29.99"/>
</Button>
</Grid>
<ListBox ItemsSource="{StaticResource personList}" DisplayMemberPath="Name"/>
<ListBox DisplayMemberPath="Age">
<ListBox.ItemsSource>
<local:PersonList>
<local:Person Name="DebugLZQ1" Age="26"/>
<local:Person Name="DebugLZQ2" Age="26"/>
</local:PersonList>
</ListBox.ItemsSource>
</ListBox>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace CreatingCustomTypeInXaml
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
} public class Person
{
public string Name { get; set; }
public int Age { get; set; }
} public class PersonList : List<Person>
{ } }

5.通过XAML构建---Static对象

MainWindowTextSettings.cs如下:

using System.Windows.Media;

namespace StaticCliassInXamlDemo
{
public class MainWindowTextSettings
{
public static double FontSize = ; public static string StringValue = "Customer customized value"; public static Brush ForeGround = new SolidColorBrush(Colors.Red);
}
}

MainWindow.xaml如下:

<Window x:Class="StaticCliassInXamlDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:oem="clr-namespace:StaticCliassInXamlDemo"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Text="{x:Static oem:MainWindowTextSettings.StringValue}"
FontSize="{x:Static oem:MainWindowTextSettings.FontSize}"
Foreground="{x:Static oem:MainWindowTextSettings.ForeGround}"
TextTrimming="CharacterEllipsis"/>
</Grid>
</Window>

效果如下:

希望对你有帮助~

WPF整理-XAML构建后台类对象的更多相关文章

  1. WPFS数据绑定(要是后台类对象的属性值发生改变,通知在“client界面与之绑定的控件值”也发生改变须要实现INotitypropertyChanged接口)

    WPFS数据绑定(要是后台类对象的属性值发生改变,通知在"client界面与之绑定的控件值"也发生改变须要实现INotitypropertyChanged接口) MainWindo ...

  2. WPF整理-XAML访问静态属性

    "XAML provides an easy way to set values of properties—type converters and the extended propert ...

  3. WPF整理-自定义一个扩展标记(custom markup extension)

    "Markup extensions are used to extend the capabilities of XAML, by providing declarativeoperati ...

  4. WPF整理-使用用户选择主题的颜色和字体

    “Sometimes it's useful to use one of the selected colors or fonts the user has chosen in theWindows ...

  5. WPF 为资源字典 添加事件响应的后台类

    原文:WPF 为资源字典 添加事件响应的后台类 前言,有许多同学在写WPF程序时在资源字典里加入了其它控件,但又想写事件来控制这个控件,但是资源字典没有CS文件,不像窗体XAML还有一个后台的CS文件 ...

  6. 整理:WPF中Xaml中绑定枚举的写法

    原文:整理:WPF中Xaml中绑定枚举的写法 目的:在Combobox.ListBox中直接绑定枚举对象的方式,比如:直接绑定字体类型.所有颜色等枚举类型非常方便 一.首先用ObjectDataPro ...

  7. WPF{ComboBox绑定类对象, 下拉列显示的值,与取到的值}

    DisplayMemberPath 是用来显示下拉列表的值 SelectedValuePath是用来取得选中项的值. ComboBox绑定类对象, 下拉列显示的值,与取到的值 string. Join ...

  8. 分享知识-快乐自己:SpringMvc整合遇到-前台传JSON参数,后台实体类对象接收

    前台数据转JSON对象: /** * * @param $myFrom:from表单 * @returns {{}} */ function from($myFrom) { var ebookEntr ...

  9. WPF系列(1)WPF和XAML基础

    终于下定决心开始更新WPF一个系列的文章,这里主要是出于两个目的,一是自己对所学的知识有一个系统的总结,二十希望能对其他人有些帮助,如果您觉得我写的不好,欢迎提意见. 那么既然我要开始写WPF,那我们 ...

随机推荐

  1. IntelliJ IDEA 14.x 快捷键/个性化设置

    常用快捷键设置(设置成跟Eclipse差不多) 按照路径:File -> Settings -> Appearance & Behavior -> Keymap -> ...

  2. poj 1192

    此题亦一眼看出算法,一次AC. 没什么好讲的,就是一个普通的树形动规. 用dp[n][0]表示n号顶点不取时的最大值,dp[n][1]表示n号顶点取时的最大值. dp[n][0]=max{dp[x][ ...

  3. word20161213

    journal queue / 日志队列 journal quota / 日志配额 junction point / 交叉点 KDC, Key Distribution Center / 密钥分发中心 ...

  4. Flask 吐血400错误

    的确地址或者method不匹配,这个容易解决 在后端中取到了form中不存在的元素! 这个很麻烦,特别form里面的信息比较多时!这个需要一一排查.另外取元素时最好用 request.form.get ...

  5. NHibernate3快速上手教程FluentNHibernate配置与DBHelper

    很多学习NHibernate的新手很容易卡在配置文件这一关,正所谓万事开头难,上手后再配合官方文档就比较容易了. 网上关于配置文件的资料非常多,但由于版本的问题,许多老的教程中都没有明确指出类库的版本 ...

  6. waxpatch修改任意类的用法

    例如:修改一个UIView(PJView)的子类和一个NSObject(PJModel)类,则需要在patch.lua文件中声明这两个要修改的类 并且建立这些待修改的类的对应的.lua文件 对应的.l ...

  7. jq表头固定

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta na ...

  8. Sublime Text 2报“Decode error - output not utf-8”错误的解决办法

    [Decode error - output not utf-8] [Decode error - output not utf-8]   应该怎么办?   这是因为python配置的编译环境的编码不 ...

  9. iOS 类微信语音播放之切换听筒和扬声器的方法解决方案

    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];   //建议在播放之前设置yes,播放结束设置NO,这个功能是 //添加监听 ...

  10. python备忘--函数

    1.zip函数 zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表. x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] xyz = zip( ...