首页 > 其他分享 >MAUI新生2.2-数据绑定和MVVM:数据绑定转换器Converter

MAUI新生2.2-数据绑定和MVVM:数据绑定转换器Converter

时间:2022-11-28 00:01:27浏览次数:29  
标签:object Converter MVVM 绑定 value 泛型 转换器 public

当绑定目标和绑定源的数据类型不一致,且无法进行隐式转换时,可以通过转换器Converter进行数据类型的转换。转换器是一个实现IValueConverter接口的类,实现Convert和ConvertBack两个方法,其中Convert方法,传入绑定源数据,返回转换后的数据给绑定目标;ConverBack则相反,传入绑定目标数据,返回转换后的数据给绑定源。

 

一、基本使用:①定义Converter类,②在Binding中,设置Converter。案例:Button的属性IsEnabled(绑定目标),绑定Entry的属性Text长度(绑定源),布尔和整数类型的绑定转换

1、定义转换器。建议将自定义的转换器,统一放到Converters文件夹下

namespace MauiApp8.Converters;

public class IntToBoolConverter : IValueConverter
{
    //Convert方法中的value参数,为绑定源数据,此例中为int类型
    //如果value为0,则返回false,否则返回true
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (int)value != 0;
    }
    //ConvertBack方法的value参数,为绑定目标数据,此例中为bool类型
    //如果value为true,则返回1,否则返回0
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)value ? 1 : 0;
    }
}

 

2、使用转换器

<ContentPage
    x:Class="MauiApp8.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:converter="clr-namespace:MauiApp8.Converters">
    <!--通过 xmlns:converter 引入转换器命名空间-->
    <!--在页面级资源字典中,创建转换器对象,字典键名为intToBool-->
    <ContentPage.Resources>
        <converter:IntToBoolConverter x:Key="intToBool" />
    </ContentPage.Resources>

    <StackLayout Padding="30">
        <Entry x:Name="entry1" Text="" Placeholder="请输入" />
<!--Binding中,通过使用Converter,绑定转换器对象--> <Button x:Name="button1" IsEnabled="{Binding Source={x:Reference entry1}, Path=Text.Length, Converter={StaticResource intToBool}}" Text="确定" />
</StackLayout> </ContentPage>

 

 

二、转换器参数:使用转换器时,可以通过ConverterParameter给转换器传参。案例:Lable的属性Text(绑定目标),绑定Entry的属性Text(绑定源,转为整数,并乘以转换器参数)

1、定义转换器

public class IntToMultipleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //转换value为整数,如果无法转换,则使用默认值0
        int valueInt = 0;
        int.TryParse(value.ToString(), out valueInt);

        //转换parameter为整数,如果无法转换,则使用默认值1
        int parameterInt = 1;
        int.TryParse(parameter.ToString(),out parameterInt);

        return valueInt * parameterInt;
    }
    //绑定模式为OneWay,不需要定义ConverBack方法
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

 

2、使用转换器

<ContentPage
    ...
    xmlns:converter="clr-namespace:MauiApp8.Converters">

    <ContentPage.Resources>
        <converter:IntToMultipleConverter x:Key="intToMultiple" />
    </ContentPage.Resources>

    <StackLayout Padding="30">
        <Entry x:Name="entry1" Text="" Keyboard="Numeric" Placeholder="请输入数据" />
        <!--通过ConverterParameter向转换器传入参数-->
        <Label x:Name="label1" Text="{Binding Source={x:Reference entry1}, 
                                              Path=Text, 
                                              Converter={StaticResource intToMultiple}, 
                                              ConverterParameter=5}" />
    </StackLayout>

</ContentPage>

 

 

三、泛型转换器:转换器类除了实现IValueConverter接口外,其它和普通类没什么区别,所以我们可以为转换器定义属性和泛型参数,在创建转换器对象时,传入属性和泛型参数值,为转换器的定义提供更多灵活性。和ConverterParameter的区别是,ConverterParameter只能传入单个值,而属性和泛型参数,可以传入更多、更丰富的值和类型。案例:Lable的属性Text和TextColor(绑定目标),绑定Switch的属性IsToggled(绑定源),绑定源的Bool类型,根据不同的绑定目标,转换为不同类型的值。

1、定义泛型转换器

//布尔类型和泛型类型之间的转换
public class BoolToObjectConverter<T> : IValueConverter
{
    //定义两个泛型属性,Bool值为true时,与TrueObject相互转换;为false时,与FalseObject相互转换
    public T TrueObject { get; set; }
    public T FalseObject { get; set; }
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)value ? TrueObject : FalseObject;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //绑定目标转为泛型T,并与TrueObject比如,如相等则返回true,否则返回false
        return ((T)value).Equals(TrueObject);
    }
}

 

2、使用泛型转换器。由于属性值比较复杂,充分使用了“属性元素”语法,如<Label.Text>、<Binding.Converter>等。

<ContentPage
    ......
    xmlns:converter="clr-namespace:MauiApp8.Converters">

    <StackLayout Padding="30">
        <Switch x:Name="switch1" /> <!--Label文本开关-->
        <Switch x:Name="switch2" /> <!--Label文本颜色开关-->
        <Label>
            <Label.Text>
                <Binding Source="{x:Reference switch1}" Path="IsToggled">
                    <Binding.Converter>
                        <converter:BoolToObjectConverter x:TypeArguments="x:String" TrueObject="Yes" FalseObject="No"/>
                    </Binding.Converter>
                </Binding>
            </Label.Text>
            <Label.TextColor>
                <Binding Source="{x:Reference switch2}" Path="IsToggled">
                    <Binding.Converter>
                        <converter:BoolToObjectConverter x:TypeArguments="Color" TrueObject="Green" FalseObject="Red"/>
                    </Binding.Converter>
                </Binding>
            </Label.TextColor>
        </Label>
    </StackLayout>

</ContentPage>

 

标签:object,Converter,MVVM,绑定,value,泛型,转换器,public
From: https://www.cnblogs.com/functionMC/p/16930927.html

相关文章

  • <四>虚函数 静态绑定 动态绑定
    代码1classBase{public: Base(intdata=10):ma(data){ cout<<"Base()"<<endl;} voidshow(){cout<<"BaseShow()"<<endl;} voidshow(int){cout<<"Bas......
  • jquery007-事件绑定的先后顺序
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>顺序</title></head><bodystyle="width:980px;margin:0auto"><h1>绑定事件先执行,a......
  • ASP.NET Core教程-Model Binding(模型绑定)
    更新记录转载请注明出处:2022年11月27日发布。2022年11月25日从笔记迁移到博客。模型绑定是什么模型绑定是指:使用来自HTTP请求的值来创建.NET对象的过程。模型绑......
  • MAUI新生2.1-数据绑定和MVVM:数据绑定基础
    一、基本概念1、数据绑定,链接两个对象的属性,其中一个对象作为绑定源,另一个对象作为绑定目标。两个链接的属性之间,可以实现双向、单向或单次等丰富的数据响应,一方数据发生......
  • java出现javax/xml/bind/DatatypeConverter错误
     今天在使用Jwt生成token的时候出现的错误,错误如下:Exceptioninthread"main"java.lang.NoClassDefFoundError:javax/xml/bind/DatatypeConverter atio.jsonwebtoken......
  • ES5 绑定 this 的方法
    this的动态切换,固然为JavaScript创造了巨大的灵活性,但也使得编程变得困难和模糊。有时,需要把this固定下来,避免出现意想不到的情况。JavaScript提供了call、apply、bind......
  • js014-一个标签绑定两个相同事件的方法
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title></head><body><divid="i1">aabbcc</div><script>vard=do......
  • 【转】WPF 中双向绑定通知机制之OBSERVABLECOLLECTION使用
    WPF中双向绑定通知机制之ObservableCollection使用msdn中  ObservableCollection<T> 类  表示一个动态数据集合,在添加项、移除项或刷新整个列表时,此集合将......
  • Repeater嵌套绑定Repeater
    privatevoidRpTypeBind(){//GetQuestionTypeAndCount()返回一个datatablethis.rptypelist.DataSource=LiftQuestionCtr.GetQuestionTypeAndCount......
  • vite+vue3批量导入静态资源图片;动态绑定大量图片
    vite版本:vite3;vue版本:vue3打包上线后发现,动态绑定的图片皆失效。单图可用import导入解决,但是若有大量图片,一一导入则耗时耗力。vue2+webpack可用require解决批量导......