WPF笔记
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笔记的更多相关文章
- WPF笔记(2.8 常用的布局属性)——Layout
原文:WPF笔记(2.8 常用的布局属性)--Layout 这一节老没意思,啰里啰唆的尽是些HTML的属性,挑几个好玩的List出来,备忘:Padding与Margin的区别:Margin指控件边界与 ...
- WPF笔记(2.9和2.10)——Layout
原文:WPF笔记(2.9和2.10)--Layout 2.9讲的是,如果内部设定超过容器大小,怎么办?StackPanel会裁剪越界部分DockPanel和Grid会智能判断,从而决定换行. 2.10 ...
- WPF笔记(2.7 文字布局)——Layout
原文:WPF笔记(2.7 文字布局)--Layout 这一节介绍的是文字布局的几个控件:1.TextBlock 最基本的文字控件可以配置5个Font属性.TextWraping属性,&quo ...
- WPF笔记(2.5 Canvas)——Layout
原文:WPF笔记(2.5 Canvas)--Layout Canvas是最精确的布局容器--绝对定位,此书作者不建议使用,以为控件的大小一般会随着内部字体图片的动态生成而自动变化,所以使用前三种布局是 ...
- WPF笔记(2.6 ViewBox)——Layout
原文:WPF笔记(2.6 ViewBox)--Layout 在Canvas外面包一层ViewBox,可以使Canvas内的控件填充整个ViewBox,并随着ViewBox的大小变化而同步变化,这是因为 ...
- WPF笔记(2.4 Grid)——Layout
原文:WPF笔记(2.4 Grid)--Layout 第一章已经简单介绍过这个容器,这一节详细介绍.Grid一般是用表格(Grid.Row 和Grid.Column )的,比StackPanel更细致 ...
- WPF笔记(2.2 DockPanel)——Layout
原文:WPF笔记(2.2 DockPanel)--Layout 读完了这一节,发现DockPanel就是过去winform中的Dock属性.原来的Dock属性是子控件设置,而其父亲级别不用设置.现在W ...
- WPF笔记(2.3 StackPanel)——Layout
原文:WPF笔记(2.3 StackPanel)--Layout StackPanel用于小规模的排版布局,比如说一个局部下几个textbox和Button啦.Orientation属性有Vertic ...
- WPF笔记(1.10 绘图)——Hello,WPF!
原文:WPF笔记(1.10 绘图)--Hello,WPF! 书中的代码语法过时了,改写为以下(测试通过): <Button> <Button.L ...
- WPF笔记(1.9 样式和控件模板)——Hello,WPF!
原文:WPF笔记(1.9 样式和控件模板)--Hello,WPF! 资源的另一个用途是样式设置: <Window > <Window.Resources> <St ...
随机推荐
- Leetcode: Number of Segments in a String
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of ...
- bzoj2251 [2010Beijing Wc]外星联络
因为n很小,所以对于串s的每一个后缀,都把其加入字典树中,并且经过一个字典树节点,该节点权值就+1. 输出时因为要字典序最小,所以字典树先走0分叉,再走1分叉,如果节点权值大于等于2就输出 代码 #i ...
- ECMAScript 6教程 (一)
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出 原文连接,博客地址为 http://www.cnblogs.com/jasonnode/ .该系列课程是 ...
- C#函数过载
什么是method?函数也.overloading,是过载的意思.为什么会过载呢?因为一个函数,本来后面拖着两个参数的,现在拖着三个参数了,那不是过载是什么? 为什么同一个函数,后面可以跟两个参数,也 ...
- 企业信息系统——CRM
客户关系管理系统(Customer Relationship Management)将客户看作是企业的一项重要资产,客户关怀是CRM的中心,其目的是与客户建立长期和有效的业务关系,在与客户的每个“接触 ...
- Windows:常见问题
1.文件(夹)非法字符 Windows系统文件(夹)非法字符"\\/:*?\"<>|",不包含‘.’,但"."字符不能是文件(夹)的首字符 ...
- mysql分区表的原理和优缺点
1.分区表的原理 分区表是由多个相关的底层表实现,这些底层表也是由句柄对象表示,所以我们也可以直接访问各个分区,存储引擎管理分区的各个底层表和管理普通表一样(所有的底层表都必须使用相同的存储引擎),分 ...
- Prince2的七大原则(6)
Prince2科普_Prince2的七大原则(6) 按照惯例我们先来回顾一下,PRINCE2七大原则分别是指:持续的业务验证,经验学习,角色与责任,按阶段管理,例外管理,关注产品,剪裁. 今天讲第六个 ...
- JSON 格式说明
一维json { "sn" : "CS20160918095444121640", "suitstypes_id" : "47&q ...
- bat命令
将DIR设置为当前文件所在的绝对路径 @echo off echo 当前盘符:%~d0 echo 当前盘符和路径:%~dp0 echo 当前盘符和路径的短文件名格式:%~sdp0 echo 当前批处理 ...