前言:为什么要用Converter呢;个人理解至少有两点:一、实现代码的解耦;二、便于复用;
以前台数据为string,后台数据为int为例,采用常规方法,可以手动转换赋值,一般数据量少的情况下,这样做的问题还不明显。但当数据量很大时,由于重复代码很多。且需要定义的变量数会多出一倍,一旦需求出现变更,就需要修改多处的代码,增大了维护负担。
0、net环境:.net core 3.1
1、工程目录如下:
2、转换器
using System;
using System.Globalization;
using System.Windows.Data;
namespace WpfApp1
{
//public ValueConversionAttribute(Type sourceType, Type targetType):指定源属性类型和目标属性类型
//Convert:会进行源属性传给目标属性的特定转化
//ConvertBack:会进行目标属性传给源属性的特定转化
//参数parameter:对应Binding的ConverterParameter属性
[ValueConversion(typeof(int), typeof(string))]
public class Integer2StrConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//throw new NotImplementedException();
int val = (int)value;
if (val == 1)
{
return "开";
}
if (val == 0)
{
return "关";
}
else
{
return "error";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
3、XAML代码
<Window
x:Class="WpfApp1.MainWindow"
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:local="clr-namespace:WpfApp1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.Resources>
<local:Integer2StrConverter x:Key="Integer2StrConverter" />
</Window.Resources>
<Grid>
<Label
x:Name="label"
Width="395"
Height="140"
Margin="190,45,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Background="#FFBD7272"
Content="{Binding Status, Converter={StaticResource Integer2StrConverter}}" />
</Grid>
</Window>
4、Code Behind:
using System.Windows;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public Class1 class1;
public MainWindow()
{
InitializeComponent();
class1 = new Class1();
label.DataContext = class1;
class1.Status = 1;
}
}
}
5、测试类Class1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace WpfApp1
{
public class Class1 : INotifyPropertyChanged
{
private int status = 0;
public int Status
{
get
{
return status;
}
set
{
status = value;
OnPropertyChanged("Status");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(String propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}