WPF——数据转换器

作者:追风剑情 发布于:2021-9-1 16:43 分类:C#

源数据与目标数据之间做转换。

示例:DataGridTextColumn与自定义类对象绑定

定义类对象

public class ActivityAdditional
{
	public string data;

	public new string ToString()
	{
		return data;
	}
}


定义数据转换器

//活动附加项转换器
public class ActivityAdditionalConverter : IValueConverter
{
	//缓成上一次正确的对象
	private object cacheValue;

	//此方法返回的值将绑定到UI上
	public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
	{
		if (value == null)
			value = new ActivityAdditional();
		cacheValue = value;
		string json = JsonConvert.SerializeObject(value);
		return json;
	}

	//UI编辑后回传时调用此方法
	public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
	{
		object modifiedValue;
		try
		{
			var settings = new JsonSerializerSettings();
			//Json中出现了C#对象中没有的成员时,抛出错误。
			settings.MissingMemberHandling = MissingMemberHandling.Error;
			modifiedValue = JsonConvert.DeserializeObject<ActivityAdditional>(value as string, settings);
			cacheValue = modifiedValue;
		}
		catch
		{
			//如果反序列化失败,则用上一次正确的值代替
			modifiedValue = cacheValue;
		}
		return modifiedValue;
	}
}


在App.xaml中定义ResourceDictionary

<Application xmlns:data="clr-namespace:DataEditor.DataObject" >
<Application.Resources>
   <ResourceDictionary>
      <data:ActivityAdditionalConverter x:Key="activityAdditionalConverter"/>
   </ResourceDictionary>
</Application.Resources>

绑定
<DataGridTextColumn Binding="{Binding Additional, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, Converter={StaticResource activityAdditionalConverter}}" MinWidth="100" Width="*" Header="附加项" />

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号