如何在<T>转换器类 wpf 中获取列表



我想使用转换器,但我不知道如何获取转换器的类端列表。

在我的 ViewModel 中,我有两个可观察集合,一个是用于绑定我的 DataGrid 项源的客户集合,另一个是用于绑定转换器的扇区集合。

public ObservableCollection<Custormer> Customers = new ObservableCollection<Customer>();
public ObservableCollection<Sector> Sectors = new ObservableCollection<Sector>();

我的 XAMl 代码如下所示

<DataGrid ItemsSource="Binding Customers" .... >
<DataGridTextColumn Header="Name">
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource ConverterNameHere}">
<Binding Path="Name" />
<Binding Path="Sectors" />
</MultiBinding>
</DataGridTextColumn.Binding>
.....
</DataGrid>

我的转换器:

public class ConverterNameHere: IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
string Name = values[0].ToString();
/* This does not work ---------------------------- */
ObservableCollection<Sector> SectorsList = new ObservableCollection<Sector>(values[1].ToList());
/* ----------------------------------------------- */
var found = SectorsList .FirstOrDefault(sector => sector.Name == Name);
if(found == null)
{
return "Not Found";
}
return Name;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

提前谢谢你

使用模式匹配is

public class ConverterNameHere : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values[0] is string name && values[1] is ObservableCollection<Sector> sectors)
{
return sectors.Any(sector => sector.Name == name) ? name : "Not Found";
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return new object[] { value, null };
}
}

您也可以修复 xaml,因为Sectors位于Window.DataContext中,而不是位于Name所在的DataGrid的项目中。Binding.Path是相对于DataContext.

<DataGrid ItemsSource="{Binding Customers}" .... >
<DataGridTextColumn Header="Name">
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource ConverterNameHere}">
<Binding Path="Name" />
<Binding Path="DataContext.Sectors" RelativeSource="{RelativeSource AncestorType=Window}" Mode="OneWay" />
</MultiBinding>
</DataGridTextColumn.Binding>
.....
</DataGrid>

并且不要忘记将转换器放在Resources

<Window.Resources>
<local:ConverterNameHere x:Key="ConverterNameHere"/>
</Window.Resources>

最新更新