65 lines
2.2 KiB
C#
65 lines
2.2 KiB
C#
using Avalonia.Data;
|
||
using Avalonia.Data.Converters;
|
||
using Avalonia.Markup.Xaml;
|
||
using System;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using System.Globalization;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace Cowain.Base.Converters;
|
||
|
||
/// <summary>
|
||
/// 通用ID到对象属性值转换器
|
||
/// 支持通过ID从集合中查找对象,并返回该对象的指定属性值
|
||
/// </summary>
|
||
public class MultiIdToPropertyConverter : MarkupExtension, IMultiValueConverter
|
||
{
|
||
public object? Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
|
||
{
|
||
try
|
||
{
|
||
// 参数说明:values[0]=ID值, values[1]=集合对象, values[2]=目标属性名(可选)
|
||
if (values.Count < 2 || values[0] is null || values[1] is null)
|
||
return BindingOperations.DoNothing;
|
||
|
||
object? id = values[0];
|
||
object? collection = values[1];
|
||
string targetProperty = (values.Count >= 3 && values[2] is string s && !string.IsNullOrEmpty(s))
|
||
? s
|
||
: "Name"; // 默认属性名为 "Name"
|
||
|
||
// 从集合中查找项
|
||
object? item = (id is not null && collection is not null) ? FindItemById(collection, id) : null;
|
||
if (item is null) return "Null";
|
||
|
||
var propertyInfo = item.GetType().GetProperty(targetProperty);
|
||
return propertyInfo?.GetValue(item) ?? "Null";
|
||
}
|
||
catch
|
||
{
|
||
return BindingOperations.DoNothing;
|
||
}
|
||
}
|
||
|
||
private object? FindItemById(object collection, object id)
|
||
{
|
||
switch (collection)
|
||
{
|
||
case IDictionary dict:
|
||
return id is not null && dict.Contains(id) ? dict[id] : null;
|
||
case IEnumerable enumerable:
|
||
foreach (var item in enumerable)
|
||
{
|
||
var itemId = item?.GetType().GetProperty("Id")?.GetValue(item);
|
||
if (itemId is not null && itemId.Equals(id))
|
||
return item;
|
||
}
|
||
break;
|
||
}
|
||
return null;
|
||
}
|
||
public override object ProvideValue(IServiceProvider serviceProvider) => this;
|
||
} |