Files
Shrlalgo.RvKits/Melskin/Converters/Internal/PropertyValueConverter.cs
2026-02-17 22:17:13 +08:00

59 lines
2.1 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Cascader.cs
using System.Globalization;
using System.Windows.Data;
namespace Melskin.Converters.Internal;
/// <summary>
/// 该类实现了 IMultiValueConverter 接口,用于将多个绑定值转换为单个输出值。特别适用于需要从数据项中动态获取属性值的场景,
/// 比如在 WPF 的 MultiBinding 中使用时,可以根据提供的属性名称动态地获取对象的属性值。
/// </summary>
internal class PropertyValueConverter : IMultiValueConverter
{
/// <summary>
/// 代表 PropertyValueConverter 类的单例实例。此实例在整个应用程序中可重用,用于在数据绑定中执行属性值转换。
/// 它特别适用于需要将多个源值(如数据项和属性名称)转换为单一输出值的情况。
/// </summary>
public static readonly PropertyValueConverter Instance = new();
/// <inheritdoc />
public object? Convert(object[]? values, Type targetType, object parameter, CultureInfo culture)
{
// 根据 MultiBinding 的定义,我们期望:
// values[0] 是当前的数据项 (例如 Staff 对象)
// values[1] 是 DisplayMemberPath 属性的值 (例如 "Name" 字符串)
if (values == null || values.Length < 2 || values[0] == null || values[1] == null)
{
return null;
}
var dataItem = values[0];
var propertyName = values[1].ToString();
if (string.IsNullOrEmpty(propertyName))
{
// 如果没有提供 DisplayMemberPath则回退到调用 .ToString()
return dataItem.ToString();
}
try
{
// 使用反射动态获取属性的值
var propertyInfo = dataItem.GetType().GetProperty(propertyName);
return propertyInfo?.GetValue(dataItem);
}
catch
{
// 如果属性不存在或发生其他错误,返回 null
return null;
}
}
/// <inheritdoc />
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}