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. Unity基于响应式编程(Reactive programming)入门

    系列目录 [Unity3D基础]让物体动起来①--基于UGUI的鼠标点击移动 [Unity3D基础]让物体动起来②--UGUI鼠标点击逐帧移动 时光煮雨 Unity3D让物体动起来③—UGUI DoT ...

  2. android IntentFilter 使用之 data过滤

    1 Intent分为两大类,显式和隐式. 显式事件,就是指通过 component Name 属性,明确指定了目标组件的事件. 比如我们新建一个Intent,指名道姓的说,此事件用于启动名为" ...

  3. JS中的prototype///////////////////////////z

    JS中的phototype是JS中比较难理解的一个部分 本文基于下面几个知识点: 1 原型法设计模式 在.Net中可以使用clone()来实现原型法 原型法的主要思想是,现在有1个类A,我想要创建一个 ...

  4. paper 101:图像融合算法及视觉艺术应用

    1:基于泊松方程的图像融合方法,利用偏微分方程实现了不同图像上区域的无缝融合.比较经典的文章: P. Pérez, M. Gangnet, A. Blake. Poisson image editin ...

  5. CSS3 border-image详解、应用

    一.border-image的兼容性 border-image可以说是CSS3中的一员大将,将来一定会大放光彩,其应用潜力真的是非常的惊人.可惜目前支持的浏览器有限,仅Firefox3.5,chrom ...

  6. 助手系列之python的FTP服务器

    电脑的OS是Win7,Python版本是2.7.9,安装了pip 因为python没有内置可用的FTP SERVER,所以先选一个第三方的组件安装上,这里我选的是pyftpdlib pip insta ...

  7. 跟着8张思维导图学习javascript

    学习的道路就是要不断的总结归纳,好记性不如烂笔头,so,下面将po出8张javascript相关的思维导图. 思维导图小tips:思维导图又叫心智图,是表达发射性思维的有效的图形思维工具 ,它简单却又 ...

  8. spring多线程与定时任务

    本篇主要描述一下spring的多线程的使用与定时任务的使用. 1.spring多线程任务的使用 spring通过任务执行器TaskExecutor来实现多线程与并发编程.通常使用ThreadPoolT ...

  9. 高性能完成端口socket服务(IOCP)

    1. Winsock IO模型之IOCP模型 来自csdn blog,版权声明:本文为博主原创文章,未经博主允许不得转载. 我这里记录下,不算转载吧 http://blog.csdn.net/lost ...

  10. xcode 中 的工程模板

    基于视图的应用程序(view-based application) 应用程序如果仅使用一个视图,应该使用这个模板.一个简单的视图控制器会管理应用程序的主视图,而界面布置则使用一个Interface B ...