WPF 绑定中Converter的应用

2024-06-22 13:08
文章标签 应用 绑定 wpf converter

本文主要是介绍WPF 绑定中Converter的应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在WPF 经常用到绑定,如果绑定的源数据和目标属性是同类型的则不需要转换。比如

            <TextBox x:Name="txt1" Background="Blue" Text="测试"/><TextBox Background="{Binding ElementName=txt1,Path=Background}" Grid.Column="1"/>
如果是不同类型的数据我们要怎么做呢?比如有一个文本框,一个按钮,我一个文本框里输入一个的数字用来代表颜色,1表示“红色”,2 表示“绿色”,3表示“蓝色”。我输入对应的数字,按钮的文字显示对应颜色。

显然这个不是同类型的数据:文本框的数据是String类型,而按钮的文字颜色是Brush类型,这个时候我们就需要用到转换器(converter)来告诉我们的banding怎么转换我们的数据。首先定义一个转换器(类),命名为Number2Color,要想实现转换的功能,必须实现IValueConverter接口中的Convert和ConvertBack两个函数。Convert函数是把我们的数据来源转换为目标数据的方法,这里就是把文本框里的string类型转换为Brush类型。我们这样实现Convert函数,(参数value就是数据来源的值,这里就是文本框中的数据,返回值就是Brush)

 public object Convert(object value, Type targetType, object parameter, CultureInfo culture){int colorValue = System.Convert.ToInt32(value);switch (colorValue){case 1:              //红色return new SolidColorBrush(Colors.Red);case 2:               //绿色return new SolidColorBrush(Colors.Green);case 3:               //蓝色return new SolidColorBrush(Colors.Blue);}return new SolidColorBrush(Colors.LawnGreen);}
ConvertBak函数我们暂时先这样实现
       public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){return new NotImplementedException();}
现在来到xaml代码,显示一个文本框和一个按钮,并把按钮的前景色绑定到文本框的文本属性上,使用自定义的Number2Color转换器,运行程序  你修改文本框中的值,会看到按钮颜色发生变化。



<Window x:Class="Converter.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:cvt="clr-namespace:Converter"Title="MainWindow" Height="350" Width="525"><Window.Resources><cvt:Number2Color x:Key="N2C"/></Window.Resources><Grid><Grid.RowDefinitions><RowDefinition Height="50"/><RowDefinition Height="50"/><RowDefinition Height="30"/><RowDefinition Height="50"/><RowDefinition/></Grid.RowDefinitions><TextBox x:Name="colorText" Text="1"  BorderBrush="Gray" BorderThickness="2" Width="200" Grid.Row="1"/><Button x:Name="testBtn" Content="测试" Width="100" Grid.Row="3" FontSize="25" Foreground="{Binding Path=Text,ElementName=colorText, Converter={StaticResource N2C}}"/></Grid>
</Window>


现在我们想实现如果按钮的文字颜色发生改变,文本框中的文字也对应改变。添加3个按钮,点击按钮的时候改变“测试”按钮的文字颜色。

<StackPanel Orientation="Horizontal"><Button Content="Red" Width="100" Foreground="Red" Click="btnClick"/><Button Content="Green" Width="100" Foreground="Green" Click="btnClick"/><Button Content="Blue" Width="100" Foreground="Blue" Click="btnClick"/></StackPanel>
        private void btnClick(object sender, RoutedEventArgs e){testBtn.Foreground = ((Button)sender).Foreground;}
运行程序,点击按钮,发现“测试”按钮文字颜色是改变了,但是文本框中的文字没有发生改变。这个和我们的绑定模式有关系,默认是单向绑定,我们应设置为双向绑定,我们为绑定增加属性:Mode=TwoWay

<Button x:Name="testBtn"  Content="测试" Width="100" Grid.Row="3" FontSize="25" Foreground="{Binding Path=Text,ElementName=colorText, Converter={StaticResource N2C}, Mode=TwoWay}"/>
此时运行程序,点击按钮发现,文字能变色,文本框内数字依然没有改变,而且按钮出现红色边框,提示错误。因为我们没有告诉程序怎么将Brush数据转换为文本数据,这正是ConvertBack要做的事情。我们之前在实现这个函数的时候是抛出一个异常,所有按钮会出现红色边框,表示不允许逆向转换。现在就让我们告诉程序怎么转换数据

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){SolidColorBrush sb = (SolidColorBrush)value;Color c = sb.Color;if (c==Colors.Red){return 1;}else if (c == Colors.Green){return 2;}else if (c==Colors.Blue){return 3;}return 0;}}
这样就能实现双向绑定了。


转换器代码

namespace Converter
{public  class Number2Color:IValueConverter{public object Convert(object value, Type targetType, object parameter, CultureInfo culture){int colorValue = System.Convert.ToInt32(value);switch (colorValue){case 1:              //红色return new SolidColorBrush(Colors.Red);case 2:               //绿色return new SolidColorBrush(Colors.Green);case 3:               //蓝色return new SolidColorBrush(Colors.Blue);}return new SolidColorBrush(Colors.LawnGreen);}public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){SolidColorBrush sb = (SolidColorBrush)value;Color c = sb.Color;if (c==Colors.Red){return 1;}else if (c == Colors.Green){return 2;}else if (c==Colors.Blue){return 3;}return 0;}}
}

前台代码

<Window x:Class="Converter.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:cvt="clr-namespace:Converter"Title="MainWindow" Height="350" Width="525"><Window.Resources><cvt:Number2Color x:Key="N2C"/></Window.Resources><Grid><Grid.RowDefinitions><RowDefinition Height="50"/><RowDefinition Height="50"/><RowDefinition Height="30"/><RowDefinition Height="50"/><RowDefinition/></Grid.RowDefinitions><TextBox x:Name="colorText" Text="1"  BorderBrush="Gray" BorderThickness="2" Width="200" Grid.Row="1"/><Button x:Name="testBtn"  Content="测试" Width="100" Grid.Row="3" FontSize="25" Foreground="{Binding Path=Text,ElementName=colorText, Converter={StaticResource N2C}, Mode=TwoWay}"/><StackPanel Orientation="Horizontal"><Button Content="Red" Width="100" Foreground="Red" Click="btnClick"/><Button Content="Green" Width="100" Foreground="Green" Click="btnClick"/><Button Content="Blue" Width="100" Foreground="Blue" Click="btnClick"/></StackPanel></Grid>
</Window>
按钮点击代码

        private void btnClick(object sender, RoutedEventArgs e){testBtn.Foreground = ((Button)sender).Foreground;}



这篇关于WPF 绑定中Converter的应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

利用Python操作Word文档页码的实际应用

《利用Python操作Word文档页码的实际应用》在撰写长篇文档时,经常需要将文档分成多个节,每个节都需要单独的页码,下面:本文主要介绍利用Python操作Word文档页码的相关资料,文中通过代码... 目录需求:文档详情:要求:该程序的功能是:总结需求:一次性处理24个文档的页码。文档详情:1、每个

Java中的分布式系统开发基于 Zookeeper 与 Dubbo 的应用案例解析

《Java中的分布式系统开发基于Zookeeper与Dubbo的应用案例解析》本文将通过实际案例,带你走进基于Zookeeper与Dubbo的分布式系统开发,本文通过实例代码给大家介绍的非常详... 目录Java 中的分布式系统开发基于 Zookeeper 与 Dubbo 的应用案例一、分布式系统中的挑战二

Java 缓存框架 Caffeine 应用场景解析

《Java缓存框架Caffeine应用场景解析》文章介绍Caffeine作为高性能Java本地缓存框架,基于W-TinyLFU算法,支持异步加载、灵活过期策略、内存安全机制及统计监控,重点解析其... 目录一、Caffeine 简介1. 框架概述1.1 Caffeine的核心优势二、Caffeine 基础2

使用Node.js和PostgreSQL构建数据库应用

《使用Node.js和PostgreSQL构建数据库应用》PostgreSQL是一个功能强大的开源关系型数据库,而Node.js是构建高效网络应用的理想平台,结合这两个技术,我们可以创建出色的数据驱动... 目录初始化项目与安装依赖建立数据库连接执行CRUD操作查询数据插入数据更新数据删除数据完整示例与最佳

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

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

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

PostgreSQL简介及实战应用

《PostgreSQL简介及实战应用》PostgreSQL是一种功能强大的开源关系型数据库管理系统,以其稳定性、高性能、扩展性和复杂查询能力在众多项目中得到广泛应用,本文将从基础概念讲起,逐步深入到高... 目录前言1. PostgreSQL基础1.1 PostgreSQL简介1.2 基础语法1.3 数据库

Python中的filter() 函数的工作原理及应用技巧

《Python中的filter()函数的工作原理及应用技巧》Python的filter()函数用于筛选序列元素,返回迭代器,适合函数式编程,相比列表推导式,内存更优,尤其适用于大数据集,结合lamb... 目录前言一、基本概念基本语法二、使用方式1. 使用 lambda 函数2. 使用普通函数3. 使用 N

Python中yield的用法和实际应用示例

《Python中yield的用法和实际应用示例》在Python中,yield关键字主要用于生成器函数(generatorfunctions)中,其目的是使函数能够像迭代器一样工作,即可以被遍历,但不会... 目录python中yield的用法详解一、引言二、yield的基本用法1、yield与生成器2、yi