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

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

被折叠的 条评论
为什么被折叠?



