Skip to main content
 首页 » 编程设计

c#之在 ViewModel 中覆盖 List.ToString()

2024年02月06日18shanyou

我有一个显示部件的数据网格。每个部分都可以有多个标识符,网格看起来像这样

Name Identifiers Size ... 
------------------------- 
P1    A,B         3 
P2    C,D         4 
P3    E           2 

在我的模型中,标识符存储在每个部分的列表中

class PartListModel { 
    public ObservableCollection<Part> Parts { get; set; } 
} 
class Part { 
    public IList<Identification> Identifications { get; set; } 
} 

但为了让它在我的 View 中正确显示,我必须向我的部分添加一个 Getter

class Part { 
    public string IdentNames {  
          get { return string.Join(",", Identifications.Select(i => i.ArticleNumber)); }  
    } 
} 

在我的 View 中显示它

<DataGridTextColumn Header="Identifiers" Binding="{Binding IdentNames}" /> 

这是我想避免的黑客行为。如何让我的 ViewModel 覆盖我的列表的 ToString() 方法,而不需要在我的模型中添加那个丑陋的 Getter?

请您参考如下方法:

一个选项(您可能会使其更通用以处理不同的情况)是创建一个值转换器来输出所需的值:

public class MyIdentificationConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, 
        object parameter, CultureInfo culture) 
    { 
        return string.Join(",",  
            ((List<MainWindowViewModel.Identification>)value).Select(x => x.ArticleNumber)); 
    } 
 
    public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture) 
    { 
        throw new NotImplementedException(); 
    } 
} 

然后在您的 XAML 中使用它:

<Window.Resources> 
    <myWpfApp:MyIdentificationConverter x:Key="MyIdentificationConverter" /> 
</Window.Resources> 
 
... 
 
<DataGridTextColumn Header="Identifiers" Binding="{Binding Path=Identifications, 
                              Converter={StaticResource MyIdentificationConverter}}" /> 

这是一个更通用的版本,使用反射来找到正确的属性:

public object Convert(object value, Type targetType, 
    object parameter, CultureInfo culture) 
{ 
    return string.Join(",", 
        (((IEnumerable<object>)value).Select(x => x.GetType() 
                                     .GetProperty(parameter.ToString()).GetValue(x)))); 
} 

再次,从 XAML 调用:(将属性作为参数传递给 select)

<DataGridTextColumn Header="Identifiers" Binding="{Binding Path=Identifications, 
                              Converter={StaticResource MyIdentificationConverter}, 
                              ConverterParameter=ArticleNumber}" />