月更
This commit is contained in:
36
AntDesignWPF/Converters/GenericConverterExtension.cs
Normal file
36
AntDesignWPF/Converters/GenericConverterExtension.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
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 AntDesign.WPF.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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user