WPF(通用转换器)

这篇博客介绍了几种在WPF应用中使用的XAML数据转换器,包括MathConverter用于字符串数值运算,DateConverter用于日期时间格式化,ImageConverter用于字节数组到BitmapImage的转换,以及MultiValueConverter实现自适应圆角按钮。这些转换器在UI展示和数据绑定中起着关键作用。

1.MathConverter

有时候我们想在XAML中对绑定的数据进行数值运算转换,就需要这个转换器了。

这个NuGet包可以使字符串进行数据运算。

using System;
using System.Globalization;
using System.Windows.Data;
using NCalc;

[ValueConversion(typeof(decimal), typeof(string))]
public class MathConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string expressionString = parameter as string;
        expressionString = expressionString.Replace(" ", "");
        expressionString = expressionString.Replace("@Value", value.ToString());
        return new Expression(expressionString).Evaluate();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
<Window x:Class="WpfApp2.Window2"
        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:WpfApp2"
        mc:Ignorable="d"
        Title="Window2" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="80"/>
        </Gri
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bridge_go

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值