《深入浅出WPF》学习笔记之二
来源:互联网 发布:打开telnet端口命令 编辑:程序博客网 时间:2024/05/18 01:24
视频地址: XAML中为对象属性赋值的语法
- xmal文件使用声明性语言,“
<window />
”表示声明一个窗体对象。 - 对象存储数据的方式:1、字段;2、属性。通常以属性的方式获取数据。
为对象属性赋值的三种方式:
一、使用Attribute=Value赋值
<Button Width="100" Height="30"/>
若属性不是字符串格式,应该怎么办呢?这个时候需要将value转换为属性类型,并赋值给对象。
- 在.cs文件中,我们新建一个Animal类
namespace HelloWPF{ public class Animal { public string name { get; set; } public Animal animal { get; set; } }}
- 在.xaml的命名空间中引用Animal所在的命名空间:
<Window x:Class="HelloWPF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:HelloWPF" Title="MainWindow" Height="350" Width="525"></Window>
- 将Animal对象作为资源声明,并为对象属性赋值
<Window.Resources> <local:Animal x:Key="animal" name="Hello Ketty"></local:Animal></Window.Resources>
<Window.Resources>
:以字典的形式维护一系列资源。
- 在xaml文件中对对象的string类型属性赋值,并在.cs文件中获取值:
Animal cat = this.FindResource("animal") as Animal;MessageBox.Show(cat.name);
- 在xaml文件中对对象的Animal类型属性赋值,并在.cs文件中获取值:
<Window.Resources> <local:Animal x:Key="animal" Name="Hello Ketty" animal="Doggy"></local:Animal> </Window.Resources>
public class Animal { public string Name { get; set; } public Animal animal { get; set; } } public class NameToAnimalTypeConverter : TypeConverter { public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { string name = value.ToString(); Animal animal = new Animal(); animal.Name = name; return animal; } }
- .cs文件中获取xaml 文件中的Animal对象的animal属性
Animal cat = this.FindResource("animal") as Animal; if (cat != null) MessageBox.Show(cat.animal.Name);
二、使用属性标签赋值
普通字符串的赋值,在封闭标签中使用Attribute=Value即可。若要对属性赋值复杂对象,可在标签内容中声明。
<Rectangle Width="30" Height="30" Stroke="DarkGreen" Fill="LightGreen"/>
以上语句实例化了一个方块:
若要将此方块放入Button的内容中,可对Button的Content属性进行赋值:
<Button Name="button" Width="150" Height="50"> <Button.Content> <Rectangle Width="30" Height="30" Stroke="DarkGreen" Fill="LightGreen"/> </Button.Content> </Button>
效果如下:
三、标签扩展赋值
首先在资源中定义一个string变量,为了定义该变量,我们引用命名空间
xmlns:sys="clr-namespace:System;assembly=mscorlib"
定义变量helloString
<Window.Resources> <sys:String x:Key="stringHello">Hello WPF!</sys:String> </Window.Resources>
在button的Content属性中通过扩展标签引用该变量:
<Button Name="button1" Width="150" Height="50" Content="{StaticResource ResourceKey=stringHello}"/>
0 0
- 《深入浅出WPF》学习笔记之二
- 《深入浅出WPF》学习笔记之三
- 学习笔记:WPF学习之深入浅出话属性
- 《深入浅出WPF》学习笔记之一
- 《深入浅出MFC》学习笔记之二
- 《深入浅出MFC》学习笔记之二
- 《深入浅出MFC》学习笔记之二
- WPF学习笔记二
- WPF学习之深入浅出话属性
- WPF学习之深入浅出话命令
- WPF学习之深入浅出话模板
- WPF学习之深入浅出话命令
- WPF学习之深入浅出话命令
- 深入浅出MFC学习笔记(二)
- 《ES6深入浅出》学习笔记(二)
- 深入浅出WPF笔记-2
- 深入浅出WPF学习(一)
- WPF学习笔记之-WPF数据绑定
- 解读vmstat中的ACTIVE/INACTIVE MEMORY
- 单例模式
- Centos6.5 oracle11gR2 rac安装
- 对数据库范式的理解
- 理解 %IOWAIT (%WIO)
- 《深入浅出WPF》学习笔记之二
- jsonc库的安装以及简单使用
- bzoj4542【HNOI2016】大数
- Eclipse发布项目默认编译输出目录改为WEB-INF/classes
- 欢迎使用CSDN-markdown编辑器
- bzoj4514【SDOI2016】数字配对
- 科学计算工具-ipython
- 【数据结构】c++实现HashTable(开链法)
- bzoj4517【SDOI2016】排列计数