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. Java Servlet(八):EL自定义函数

    EL自定义函数:在EL表达式中调用的某个java类的静态方法,这个静态方法需在web应用程序中进行配置才可以被EL表达式调用. EL自定义函数可以扩展EL表达式的功能,让EL表达式完成普通java程序 ...

  2. mssql手工注入及绕过术

      报错注入: - 例子:http://www.kfgtfcj.xxx.cn/lzygg/Zixun_show.aspx?id=1 [1]首先爆版本:http://www.kfgtfcj.xxx.cn ...

  3. image -- pmp

  4. 移动前端中viewport(视口) 转

    移动前端中常说的 viewport (视口)就是浏览器显示页面内容的屏幕区域.其中涉及几个重要概念是 dpi ( device-independent pixel 设备逻辑像素 )和 CSS 像素之间 ...

  5. Orchard使用中的坎坎坷坷

    千万不要删除 内容类型为 Page 的 Welcome to Orchard!,删除之后的问题就大发了,首页就打不开. 如果没发布也会出现首页打不开的现象!!!

  6. [转]网络诊断工具:MTR

    MTR是Linux平台上一款非常好用的网络诊断工具,集成了traceroute.ping.nslookup的功能,用于诊断网络状态非常有用.能按要求对路由中所有节点进行批量测试 第一列(Host):I ...

  7. [转]Git调用第三方对比工具beyondCompare

    点击阅读原文 对于我这种 git 命令行小白来说, git 自带的对比工具各种水土不服,想念以前的 svn 小乌龟 + beyondCompare 的日子...纠结完 gitHub client 未果 ...

  8. Android 进阶Android 中的 IOC 框架 【ViewInject】 (上)

    1.概述 首先我们来吹吹牛,什么叫IoC,控制反转(Inversion of Control,英文缩写为IoC),什么意思呢? 就是你一个类里面需要用到很多个成员变量,传统的写法,你要用这些成员变量, ...

  9. python异常和错误(syntax errors 和 exceptions)

    语法错误 语法错误又被称解析错误 >>> for i in range(1..10):print(i) File "<stdin>", line 1 ...

  10. selenium处理Ajax浮动框方法

    package com.allin.pc;import java.util.List;import org.openqa.selenium.WebElement;import org.openqa.s ...