wpf ListView项目-基于不是项目类一部分的条件生成列值

brgchamk  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(170)

假设我有一个简单的模型类:

public class Car
{
    public string Make { get; init; }
    public string Model { get; init; }
    public string Year { get; init; }
}

在我的ViewModel中,我有两个列表:

public class ViewModel
{
    public ObservableCollection<Car> Cars { get; }
    public List<Car> CanBeSold { get; }

    public ViewModel()
    {
        Car car1 = new() { Make = "Toyota", Model = "Corolla", Year = "2020" };
        Car car2 = new() { Make = "Honda", Model = "Civic", Year = "2021" };
        Car car3 = new() { Make = "Mitsubishi", Model = "Lancer", Year = "2017" };

        Cars = new();
        CanBeSold = new();

        Cars.Add(car1);
        Cars.Add(car2);
        Cars.Add(car3);

        CanBeSold.Add(car2);
    }
}

在我看来,我正在向Cars集合出价ListView

<ListView ItemsSource="{Binding Cars}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Make" DisplayMemberBinding="{Binding Path=Make}"/>
            <GridViewColumn Header="Model" DisplayMemberBinding="{Binding Path=Model}"/>
            <GridViewColumn Header="Year" DisplayMemberBinding="{Binding Path=Year}"/>
            <GridViewColumn Header="Can Be Sold"/>
        </GridView>
    </ListView.View>
</ListView>

如果CarCanBeSold列表中,我如何显示Yes/No

谢谢你的帮助

webghufk

webghufk1#

你可以使用一个MultiBinding,它包含一个到父视图模型的CanBeSold属性的Binding和一个到当前Car元素的Binding。

<GridViewColumn Header="Can Be Sold">
    <GridViewColumn.DisplayMemberBinding>
        <MultiBinding>
            <MultiBinding.Converter>
                <local:ListElementConverter/>
            </MultiBinding.Converter>
            <Binding Path="DataContext.CanBeSold"
                     RelativeSource="{RelativeSource AncestorType=ListView}"/>
            <Binding />
        </MultiBinding>
    </GridViewColumn.DisplayMemberBinding>
</GridViewColumn>

绑定转换器检查元素是否包含在列表中:

public class ListElementConverter : IMultiValueConverter
{
    public object Convert(
        object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.Length == 2 &&
            values[0] is IList list &&
            list.Contains(values[1])
            ? "Yes"
            : "No";
    }

    public object[] ConvertBack(
        object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
rpppsulh

rpppsulh2#

我会这样做:我将创建一个新类CarExt,其中包括类Car,以及一个额外的get属性“can the car be sold”,该属性通过在列表CanBeSold中查找汽车来计算。我将类CarExt绑定到 ListView ItemsSource

相关问题