37 lines
1.1 KiB
C#
37 lines
1.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Data;
|
|
using System.Windows.Markup;
|
|
|
|
namespace AntDesignWPF.Converters;
|
|
|
|
/// <summary>
|
|
/// 构造单例的Converter的markup
|
|
/// </summary>
|
|
/// <example>
|
|
/// 示例代码:
|
|
/// <code>
|
|
/// <![CDATA[<TextBlock Text="{Binding Value, Converter={local:GenericConverterExtension Type={x:Type local:MyValueConverter}}}" />]]>
|
|
/// </code>
|
|
/// </example>
|
|
public class GenericConverterExtension : MarkupExtension
|
|
{
|
|
public Type Type { get; set; }
|
|
|
|
private static readonly Dictionary<Type, object> _instances = new();
|
|
public override object ProvideValue(IServiceProvider serviceProvider)
|
|
{
|
|
if (Type == null || !typeof(IValueConverter).IsAssignableFrom(Type)|| !typeof(IMultiValueConverter).IsAssignableFrom(Type))
|
|
throw new InvalidOperationException("类型必须是值转换器");
|
|
|
|
if (!_instances.TryGetValue(Type, out var instance))
|
|
_instances[Type] = instance = Activator.CreateInstance(Type);
|
|
|
|
return instance;
|
|
}
|
|
}
|
|
|