《深入浅出WPF》读书笔记.6binding系统(下)

2024-08-25 09:04

本文主要是介绍《深入浅出WPF》读书笔记.6binding系统(下),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《深入浅出WPF》读书笔记.6binding系统(下)

背景

主要讲数据校验和数据转换以及multibinding

代码

binding的数据校验

<Window x:Class="BindingSysDemo.ValidationRulesDemo"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:BindingSysDemo"mc:Ignorable="d"Title="ValidationRulesDemo" Height="200" Width="400"><StackPanel VerticalAlignment="Center"><TextBox x:Name="tb1" Margin="5"></TextBox><Slider x:Name="sld1" Minimum="-10" Maximum="110" Margin="5"></Slider></StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;namespace BindingSysDemo
{/// <summary>/// ValidationRulesDemo.xaml 的交互逻辑/// </summary>public partial class ValidationRulesDemo : Window{public ValidationRulesDemo(){InitializeComponent();Binding binding = new Binding("Value") { Source = this.sld1, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };RangeValidationRule rule = new RangeValidationRule();//此参数用来校验source数据rule.ValidatesOnTargetUpdated = true;binding.ValidationRules.Add(rule);//通过路由事件获取校验的报错信息//信号在UI树上传递的过程乘坐路由事件binding.NotifyOnValidationError = true;this.tb1.SetBinding(TextBox.TextProperty, binding);//监听校验失败错误this.tb1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(this.ValidationError));}private void ValidationError(object sender, RoutedEventArgs e){if (Validation.GetErrors(this.tb1).Count > 0){this.tb1.ToolTip = Validation.GetErrors(this.tb1)[0].ErrorContent.ToString();}}}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;namespace BindingSysDemo
{public class RangeValidationRule : ValidationRule{public override ValidationResult Validate(object value, CultureInfo cultureInfo){//throw new NotImplementedException();double d = 0;if (double.TryParse(value.ToString(), out d)){if (d >= 0 && d <= 100){return new ValidationResult(true, null);}}return new ValidationResult(false, "Validation failed!");}}
}

binding的数据转换

<Window x:Class="BindingSysDemo.BindingConverterDemo"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:BindingSysDemo"mc:Ignorable="d"Title="BindingConverterDemo" Height="500" Width="600"><Window.Resources><local:Category2SourceConverter x:Key="c2s"></local:Category2SourceConverter><local:State2NullableBoolConverter x:Key="s2b"></local:State2NullableBoolConverter></Window.Resources><StackPanel Background="AliceBlue"><ListBox x:Name="listBoxPlane" Height="300" Margin="5"><ListBox.ItemTemplate><DataTemplate><StackPanel Orientation="Horizontal"><Image Width="40" Height="20" Source="{Binding Path=Category, Converter={StaticResource c2s}}"></Image><TextBlock Text="{Binding Path=Name}" Width="60" Margin="80,0"></TextBlock><CheckBox IsThreeState="True" IsChecked="{Binding Path=State, Converter={StaticResource s2b}}"></CheckBox></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox><Button x:Name="btnLoad" Content="Load" Height="25" Margin="5" Click="btnLoad_Click"></Button><Button x:Name="btnSave" Content="Save" Height="25" Margin="5" Click="btnSave_Click"></Button></StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;namespace BindingSysDemo
{/// <summary>/// BindingConverterDemo.xaml 的交互逻辑/// </summary>public partial class BindingConverterDemo : Window{public BindingConverterDemo(){InitializeComponent();}private void btnLoad_Click(object sender, RoutedEventArgs e){List<Plane> planes = 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.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 = planes;}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));}File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "PlaneList.txt", sb.ToString());MessageBox.Show("保存成功!");}}public enum Category{Bomber,Fighter}public enum State{Available,Locked,Unknown}public class Plane{public Category Category { get; set; }public State State { get; set; }public string Name { get; set; }}}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;namespace BindingSysDemo
{public class Category2SourceConverter : IValueConverter{//将Category转换成Uripublic object Convert(object value, Type targetType, object parameter, CultureInfo culture){Category category = (Category)value;switch (category){case Category.Fighter:return @"\Icon\Fighter.png";case Category.Bomber:return @"\Icon\Bomber.png";default:return null;}}//不会被调用public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){throw new NotImplementedException();}}public class State2NullableBoolConverter : IValueConverter{//将State转换成boolpublic object Convert(object value, Type targetType, object parameter, CultureInfo culture){State state = (State)value;switch (state){case State.Locked:return false;case State.Available:return true;case State.Unknown:default:return null;}}//不会被调用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;}}}
}

multibinding

当页面显示信息不仅由一个控件来决定,就可以使用multibinding。凡是使用binding的地方都可以使用multibinding

<Window x:Class="BindingSysDemo.MultiBindingDemo"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:BindingSysDemo"mc:Ignorable="d"Title="MultiBindingDemo" Height="400" Width="600"><StackPanel><TextBox x:Name="tb1" Height="23" Margin="5"></TextBox><TextBox x:Name="tb2" Height="23" Margin="5"></TextBox><TextBox x:Name="tb3" Height="23" Margin="5"></TextBox><TextBox x:Name="tb4" Height="23" Margin="5"></TextBox><Button x:Name="btn1" Content="Submit" Width="80" Margin="5"></Button></StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;namespace BindingSysDemo
{/// <summary>/// MultiBindingDemo.xaml 的交互逻辑/// </summary>public partial class MultiBindingDemo : Window{public MultiBindingDemo(){InitializeComponent();this.SetMultiBinding();}private void SetMultiBinding(){//准备基础bindingBinding b1 = new Binding("Text") { Source = this.tb1 };Binding b2 = new Binding("Text") { Source = this.tb2 };Binding b3 = new Binding("Text") { Source = this.tb3 };Binding b4 = new Binding("Text") { Source = this.tb4 };//multibindingMultiBinding mb = new MultiBinding();mb.Bindings.Add(b1);mb.Bindings.Add(b2);mb.Bindings.Add(b3);mb.Bindings.Add(b4);mb.Converter = new LoginMultiBindingConverter();this.btn1.SetBinding(Button.IsEnabledProperty, mb);}}public class LoginMultiBindingConverter : IMultiValueConverter{public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){if (!values.Cast<string>().Any(o => string.IsNullOrEmpty(o)) && values[0].ToString() == values[2].ToString()&& values[1].ToString() == values[3].ToString()){return true;}return false;}public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture){throw new NotImplementedException();}}}

git代码

GitHub - wanghuayu-hub2021/WpfBookDemo: 深入浅出WPF的demo


这章完结了,顺手点个赞老铁。

这篇关于《深入浅出WPF》读书笔记.6binding系统(下)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1105125

相关文章

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

JWT + 拦截器实现无状态登录系统

《JWT+拦截器实现无状态登录系统》JWT(JSONWebToken)提供了一种无状态的解决方案:用户登录后,服务器返回一个Token,后续请求携带该Token即可完成身份验证,无需服务器存储会话... 目录✅ 引言 一、JWT 是什么? 二、技术选型 三、项目结构 四、核心代码实现4.1 添加依赖(pom

基于Python实现自动化邮件发送系统的完整指南

《基于Python实现自动化邮件发送系统的完整指南》在现代软件开发和自动化流程中,邮件通知是一个常见且实用的功能,无论是用于发送报告、告警信息还是用户提醒,通过Python实现自动化的邮件发送功能都能... 目录一、前言:二、项目概述三、配置文件 `.env` 解析四、代码结构解析1. 导入模块2. 加载环

linux系统上安装JDK8全过程

《linux系统上安装JDK8全过程》文章介绍安装JDK的必要性及Linux下JDK8的安装步骤,包括卸载旧版本、下载解压、配置环境变量等,强调开发需JDK,运行可选JRE,现JDK已集成JRE... 目录为什么要安装jdk?1.查看linux系统是否有自带的jdk:2.下载jdk压缩包2.解压3.配置环境

Linux查询服务器系统版本号的多种方法

《Linux查询服务器系统版本号的多种方法》在Linux系统管理和维护工作中,了解当前操作系统的版本信息是最基础也是最重要的操作之一,系统版本不仅关系到软件兼容性、安全更新策略,还直接影响到故障排查和... 目录一、引言:系统版本查询的重要性二、基础命令解析:cat /etc/Centos-release详

更改linux系统的默认Python版本方式

《更改linux系统的默认Python版本方式》通过删除原Python软链接并创建指向python3.6的新链接,可切换系统默认Python版本,需注意版本冲突、环境混乱及维护问题,建议使用pyenv... 目录更改系统的默认python版本软链接软链接的特点创建软链接的命令使用场景注意事项总结更改系统的默

在Linux系统上连接GitHub的方法步骤(适用2025年)

《在Linux系统上连接GitHub的方法步骤(适用2025年)》在2025年,使用Linux系统连接GitHub的推荐方式是通过SSH(SecureShell)协议进行身份验证,这种方式不仅安全,还... 目录步骤一:检查并安装 Git步骤二:生成 SSH 密钥步骤三:将 SSH 公钥添加到 github

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

Linux系统中查询JDK安装目录的几种常用方法

《Linux系统中查询JDK安装目录的几种常用方法》:本文主要介绍Linux系统中查询JDK安装目录的几种常用方法,方法分别是通过update-alternatives、Java命令、环境变量及目... 目录方法 1:通过update-alternatives查询(推荐)方法 2:检查所有已安装的 JDK方

Linux系统之lvcreate命令使用解读

《Linux系统之lvcreate命令使用解读》lvcreate是LVM中创建逻辑卷的核心命令,支持线性、条带化、RAID、镜像、快照、瘦池和缓存池等多种类型,实现灵活存储资源管理,需注意空间分配、R... 目录lvcreate命令详解一、命令概述二、语法格式三、核心功能四、选项详解五、使用示例1. 创建逻