1、使用TypeConvert类将XAML标签的Attribute与对象的Propety进行映射

由于XAML所有属性=属性值,其中属性值必须是字符串,当属性值不是字符串时需要添加将该属性值转换成字符串的转换器,如下Human类child的Human类情况

<Window x:Class="WPF.TypeConvertFromProperty"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Entity="clr-namespace:Entity;assembly=Entity"
Title="TypeConvertFromProperty" Height="300" Width="300">
<Window.Resources>
<Entity:Human x:Key="human" Child="ABC"/>
</Window.Resources>
</Window>
[TypeConverter(typeof(StringToHumanTypeConverter))]
public class Human
{
public string Name { get; set; }
public Human Child { get; set; }
} public class StringToHumanTypeConverter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
Human h = new Human();
h.Name = value as string;
return h;
}
return base.ConvertFrom(context, culture, value);
}
}

2、x:Attribute

①x:Class

告诉编译器xaml标签的编译结果与后台代码中指定的类合并

②x:ClassModifier

由标签生成的类的访问控制级别,如internal,public,private

③x:FieldModifier

标签的访问控制级别,如<TextBox x:Name="textbox"  x:FieldModifier="public"/>

④x:Share

3、布局

主要布局控件有:Grid,StackPanel,Cavas DockPanel,WrapPanel

4、Binding对数据的校验

<Window x:Class="WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Entity="clr-namespace:Entity;assembly=Entity"
Title="MainWindow" Height="" Width=""> <StackPanel>
<TextBox x:Name="textbox1" Margin=""/>
<Slider x:Name="slider1" Minimum="" Maximum="" Margin=""/>
</StackPanel>
</Window>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data; namespace WPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Binding binding = new Binding("Value") {Source=this.slider1 };
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
RangeValidationRule rvr = new RangeValidationRule();
rvr.ValidatesOnTargetUpdated = true;//设置Source出错时也校验,Binding只有在Target被外部方法改变时才校验
binding.ValidationRules.Add(rvr);//添加校验
binding.NotifyOnValidationError = true;//设置校验失败时Binding发出一个信号 this.textbox1.SetBinding(TextBox.TextProperty, binding);
this.textbox1.AddHandler(Validation.ErrorEvent,new RoutedEventHandler(this.ValidationErro));//添加侦听校验处理事件
} //侦听校验处理事件
private void ValidationErro(object sender, RoutedEventArgs e)
{
if(Validation.GetErrors(this.textbox1).Count>)
{
this.textbox1.ToolTip = Validation.GetErrors(this.textbox1)[].ErrorContent.ToString();
}
} } /// <summary>
/// 校验类
/// </summary>
public class RangeValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
double d = ;
if(double.TryParse(value.ToString(),out d))
{
if(d>&&d<)
{
return new ValidationResult(true, null);
}
}
return new ValidationResult(false, "validation fail");
}
}
}

5、Binding对数据的转换

当Source里的数据是X,Y,N时,UI上对应的是CheckBox控件的IsChecked属性值时此时我们需要手动写一个Converter类(称为数据转换器)来转换,方法是创建一个类并让这个类实现IValueConverter接口。此时当数据从Binding的Source流向target时,Convert方法被调用,反之ConvertBack方法被调用

using System;

namespace WPF.Entity
{
class Plane
{
public Category Category { get; set; } public State State { get; set; } public string Name { get; set; } } public enum Category
{
Bomber,
Figher
} public enum State
{
Available,
Locked,
Unknown
}
} using System;
using System.Windows.Data;
namespace WPF.Entity
{
/// <summary>
/// Category数据转换器
/// </summary>
public class CategoryToSourceConverter : IValueConverter
{ public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Category c = (Category)value;
switch (c)
{
case Category.Bomber:
return @"\Icons\Bomber.jpg";
case Category.Figher:
return @"\Icons\Fligter.jpg";
default:
return null;
}
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
} /// <summary>
/// State数据转换器
/// </summary>
public class StateToNullableBool:IValueConverter
{ public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
State s = (State)value;
switch (s)
{
case State.Available:
return true;
case State.Locked:
return false;
case State.Unknown:
default:
return null;
}
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool? b = (bool?)value;
switch (b)
{
case true:
return State.Available;
case false:
return State.Locked;
case null:
default:
return State.Unknown;
}
}
}
}
<Window x:Class="WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:LocalEntity="clr-namespace:WPF.Entity"
Title="MainWindow" Height="" Width="">
<Window.Resources>
<LocalEntity:CategoryToSourceConverter x:Key="cts"/>
<LocalEntity:StateToNullableBool x:Key="stab"/>
</Window.Resources>
<StackPanel>
<ListBox x:Name="listboxPlane" Height="" Margin="">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Width="" Height="" Source="{Binding Path=Category,Converter={StaticResource cts}}"/><!--数据转换器以静态资源进行引用-->
<TextBlock Text="{Binding Name}" Width="" Margin="80,0"/>
<CheckBox IsThreeState="True" IsChecked="{Binding Path=State,Converter={StaticResource stab}}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button x:Name="btnLoad" Content="Load" Height="" Margin="5,0" Click="btnLoad_Click"/>
<Button x:Name="btnSave" Content="Save" Height="" Margin="5,5" Click="btnSave_Click"/>
</StackPanel>
</Window>
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WPF.Entity;
using System; namespace WPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent(); } /// <summary>
/// Load按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
List<Plane> planeList = new List<Plane>()
{
new Plane(){Category=Category.Bomber,Name="B-1",State=State.Unknown},
new Plane(){Category=Category.Bomber,Name="B-2",State=State.Unknown},
new Plane(){Category=Category.Figher,Name="F-22",State=State.Unknown},
new Plane(){Category=Category.Figher,Name="F-Su47",State=State.Unknown},
new Plane(){Category=Category.Bomber,Name="B-52",State=State.Unknown},
new Plane(){Category=Category.Figher,Name="F-J10",State=State.Unknown},
};
this.listboxPlane.ItemsSource = planeList;
} /// <summary>
/// 保存按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, RoutedEventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (Plane p in listboxPlane.Items)
{
sb.AppendLine(string.Format("Category={0},Name={1},State={2}",p.Category,p.Name,p.State));
}
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"PlaneList.txt");
File.WriteAllText(filePath,sb.ToString());
} }
}

WPF笔记的更多相关文章

  1. WPF笔记(2.8 常用的布局属性)——Layout

    原文:WPF笔记(2.8 常用的布局属性)--Layout 这一节老没意思,啰里啰唆的尽是些HTML的属性,挑几个好玩的List出来,备忘:Padding与Margin的区别:Margin指控件边界与 ...

  2. WPF笔记(2.9和2.10)——Layout

    原文:WPF笔记(2.9和2.10)--Layout 2.9讲的是,如果内部设定超过容器大小,怎么办?StackPanel会裁剪越界部分DockPanel和Grid会智能判断,从而决定换行. 2.10 ...

  3. WPF笔记(2.7 文字布局)——Layout

    原文:WPF笔记(2.7 文字布局)--Layout 这一节介绍的是文字布局的几个控件:1.TextBlock      最基本的文字控件可以配置5个Font属性.TextWraping属性,&quo ...

  4. WPF笔记(2.5 Canvas)——Layout

    原文:WPF笔记(2.5 Canvas)--Layout Canvas是最精确的布局容器--绝对定位,此书作者不建议使用,以为控件的大小一般会随着内部字体图片的动态生成而自动变化,所以使用前三种布局是 ...

  5. WPF笔记(2.6 ViewBox)——Layout

    原文:WPF笔记(2.6 ViewBox)--Layout 在Canvas外面包一层ViewBox,可以使Canvas内的控件填充整个ViewBox,并随着ViewBox的大小变化而同步变化,这是因为 ...

  6. WPF笔记(2.4 Grid)——Layout

    原文:WPF笔记(2.4 Grid)--Layout 第一章已经简单介绍过这个容器,这一节详细介绍.Grid一般是用表格(Grid.Row 和Grid.Column )的,比StackPanel更细致 ...

  7. WPF笔记(2.2 DockPanel)——Layout

    原文:WPF笔记(2.2 DockPanel)--Layout 读完了这一节,发现DockPanel就是过去winform中的Dock属性.原来的Dock属性是子控件设置,而其父亲级别不用设置.现在W ...

  8. WPF笔记(2.3 StackPanel)——Layout

    原文:WPF笔记(2.3 StackPanel)--Layout StackPanel用于小规模的排版布局,比如说一个局部下几个textbox和Button啦.Orientation属性有Vertic ...

  9. WPF笔记(1.10 绘图)——Hello,WPF!

    原文:WPF笔记(1.10 绘图)--Hello,WPF! 书中的代码语法过时了,改写为以下(测试通过):         <Button>            <Button.L ...

  10. WPF笔记(1.9 样式和控件模板)——Hello,WPF!

    原文:WPF笔记(1.9 样式和控件模板)--Hello,WPF! 资源的另一个用途是样式设置: <Window >  <Window.Resources>    <St ...

随机推荐

  1. ASP.NET MVC 3 CheckBoxList 的使用

    在以前的 ASP.NET MVC 中可以直接使用 CheckBoxList,但后来不知道什么原因在 MVC 中移除了 CheckBoxList,所以默认情况下 ASP.NET MVC 3 中是没有 C ...

  2. HTML 5 的data-* 自定义属性

    HTML 5 增加了一项新功能是 自定义数据属性 ,也就是  data-* 自定义属性.在HTML5中我们可以使用以 data- 为前缀来设置我们需要的自定义属性,来进行一些数据的存放.当然高级浏览器 ...

  3. static const vs. extern const

    在实现文件(.m文件)中使用static const来定义“只在编译单元内可见的常量”(只在.m文件内可见),由于此类常量不在全局符号表中,所以无须为其名称加类名前缀(一般以k开头). 在头文件中使用 ...

  4. 第一册解说and表现

    综合日语第一册第五单元到十五单元的解说表现大集会:(这么一来一本书都被我搬上来啦--) 第五课 1.始めました: 初次见面时的寒暄用语,表示“初次见面(请多多观照)”之意. 2.どうぞよろしく: 用于 ...

  5. [linux系统]--Sed

    删除:d命令 $ sed ‘2d’ example—–删除example文件的第二行. $ sed ‘2,$d’ example—–删除example文件的第二行到末尾所有行. $ sed ‘$d’ ...

  6. JFrame中setDefaultCloseOperation的参数含义

    实例1:一个空的java窗口 // JFrameDemo1.java import javax.swing.*;     //使用Swing类,必须引入Swing包 public class JFra ...

  7. 2016.8.16 Java培训第一天

    1. 十进制转换二进制 31/2=15余1  15/2=7余1 7/2=3余1 3/2=1余1    31的二进制结果为11111 35/2=17余1  17/2=8余1  8/2=4余0 4/2=2 ...

  8. placeholder兼容ie8

    <script type="text/javascript">     if( !('placeholder' in document.createElement('i ...

  9. jQuery 遍历(上)

    目录: 一:定义二:遍历 DOM三:jQuery 参考手册 - 遍历 定义:什么是遍历?jQuery 遍历,意为"移动",用于根据其相对于其他元素的关系来"查找" ...

  10. ucenter的单点登录

    所谓单点登录,无非就是几个站点共用一个用户中心,实现同步登陆,同步退出. 服务器端:Loog SSO . 客服端: ucenter,说实话dz商业化确实让php发展了不少. ucenter 基本原理: ...