博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
学习WPF之 Binding
阅读量:4843 次
发布时间:2019-06-11

本文共 7561 字,大约阅读时间需要 25 分钟。

最近在学习WPF,通过看书,敲代码和做笔记等各种方式.昨天学习完了Binding这一章... ... 画了张图进行总结,以备遗忘时查看.

 

 

 1.Binding数据的校验

        
public _02Binding_ValidationRules()        {            InitializeComponent();            Binding binding = new Binding("Value") { Source = slider1, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };             RangeValidationRule rvr = new RangeValidationRule();            rvr.ValidatesOnTargetUpdated = true;            binding.ValidationRules.Add(rvr);            binding.NotifyOnValidationError = true;             textBox1.SetBinding(TextBox.TextProperty, binding);             this.textBox1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(ValidationError));            //this.slider1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(ValidationError2));        }         void ValidationError(Object sender, RoutedEventArgs e)        {            if (Validation.GetErrors(this.textBox1).Count > 0)            { textBox1.ToolTip = Validation.GetErrors(this.textBox1)[0].ErrorContent.ToString(); }        }          public class RangeValidationRule : ValidationRule    {        public override ValidationResult Validate(object value, CultureInfo cultureInfo)        {            double d;            if (double.TryParse(value.ToString(), out d))            {                if (d >= 0 && d <= 100)                {                    return new ValidationResult(true, null);                }            }              return new ValidationResult(false, "验证失败!");        }    }

 

 

   2.Binding的数据转换

 
(效果图)
 
 
C#  ///     /// 种类    ///     public enum Category    {        Bomber,        Fighter    }     ///     /// 状态    ///     public enum State    {        Available,        Locked,        Unknown    }     ///     /// 飞机类    ///     public class Plane    {        public string Name { get; set; }         public Category Category { get; set; }         public State State { get; set; }     }   C# 窗体.cs  ///         /// 给ListBox的ItemsSource属性赋值        ///         ///         ///         private void buttonLoad_Click(object sender, RoutedEventArgs e)        {            ObservableCollection
planeList = new ObservableCollection
() { 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.Fighter,Name="F-22",State=State.Unknown}, new Plane(){Category=Category.Fighter,Name="Su-47",State=State.Unknown}, new Plane(){Category=Category.Bomber,Name="B-52",State=State.Unknown}, new Plane(){Category=Category.Fighter,Name="J-10",State=State.Unknown}, }; this.listBoxPlane.ItemsSource=planeList; } private void buttonSave_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)); } File.WriteAllText(@"D:\PlaneList.txt",sb.ToString()); MessageBox.Show("OK"); }

 

 
C# 转换类 需要IValueConverter接口
Convert函数为源到目标时调用
ConvertBack函数为目标到源时调用
 
 
 
public class CategoryToSourceConverter : IValueConverter    {        //将Category转换为Uri        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)        {            Category c = (Category)value;            switch (c)            {                case Category.Bomber:                    return @"Icons\Bomber.png";                 case Category.Fighter:                    return @"Icons\Fighter.png";                 default:                    return null;            }        }         public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)        {            throw new NotImplementedException();        }    }       public class StateToNullabelBoolConverter : IValueConverter    {          ///         ///将State转换为Bool        ///         ///         ///         ///         ///         /// 
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { State s = (State)value; switch (s) { case State.Available: return true; case State.Locked: return false; case State.Unknown: default: return null; } } /// /// 将Bool转换为State /// /// /// /// /// ///
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { bool? nb = (bool?)value; switch (nb) { case true: return State.Available; case false: return State.Locked; case null: default: return State.Unknown; } } } Xaml

 


3.MultiBinding(多路Binding)

 
 
 
 
C# namespace MyTestWPFApplication._2015年9月16日 {    ///     /// _04MultiBinding.xaml 的交互逻辑    ///     public partial class _04MultiBinding : Window    {        public _04MultiBinding()        {            InitializeComponent();            SetMultiBinding();        }          void SetMultiBinding()        {            Binding b1 = new Binding("Text") { Source = textBox1 };            Binding b2 = new Binding("Text") { Source = textBox2 };            Binding b3 = new Binding("Text") { Source = textBox3 };            Binding b4 = new Binding("Text") { Source = textBox4 };             MultiBinding mb = new MultiBinding() { Mode = BindingMode.OneWay };            mb.Bindings.Add(b1);            mb.Bindings.Add(b2);            mb.Bindings.Add(b3);            mb.Bindings.Add(b4);             mb.Converter = new LogonMultiBindingConverter();            button1.SetBinding(Button.IsEnabledProperty, mb);        }    }   //因为这里的Converter类是是用来给MultiBinding的Converter来指定的.所以继承的接口不再是IValueConverter而是IMultiValueConverter    class LogonMultiBindingConverter : IMultiValueConverter    {                public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)        {             if (!values.Cast
().Any(text => string.IsNullOrEmpty(text)) && values[0].ToString() == values[1].ToString() && values[2].ToString() == values[3].ToString()) { return true; } return false; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } XAML

 

 
 
   

Binding学完了!

转载于:https://www.cnblogs.com/henhaoji/p/4815792.html

你可能感兴趣的文章
Android 软键盘弹出时布局内指定内容上移实现及问题解决
查看>>
Oracle游标动态赋值
查看>>
LVS的DR模式
查看>>
Node.js初识
查看>>
IOS开关效果
查看>>
使用Mybatis-Generator自动生成Dao、Model、Mapping相关文件(转)
查看>>
TextView控件使用小技巧
查看>>
MySQL_基础_变量
查看>>
学习计划
查看>>
OpenCV学习总结(4)- 目标跟踪
查看>>
使用mockjs模拟后端返回的json数据;
查看>>
结队-贪吃蛇-项目进度
查看>>
vim的查找字符串
查看>>
UIALertView与UIAlertViewDelegate的基本用法
查看>>
数字货币量化教程——构造金融数据的数据结构
查看>>
sql 语句中join的类型及区别小记
查看>>
OE worldwind编码 遍历文件
查看>>
TestLink 的使用详解
查看>>
Ubuntu 常用命令
查看>>
python 安装模块
查看>>