包含List <object>作为项目源的DisplayMember组合框

时间:2019-05-29 06:02:17

标签: c# wpf mvvm

我有Comobox喜欢这个

 <dxe:ComboBoxEdit AutoComplete="True" IsTextEditable="False" ImmediatePopup="True" IncrementalFiltering="True" ItemsSource="{Binding Example}" />

在Vm中

 public List<object> Example
            {
                get { return example; }
                set { example = value; OnPropertyChanged(new PropertyChangedEventArgs("Example")); }
            }
   public List<ArticlesStock> ArticlesStockList
        {
            get { return articlesStockList; }
            set
            {
                articlesStockList = value;
                OnPropertyChanged(new PropertyChangedEventArgs("ArticlesStockList"));
            }
        }

  Example.Add(ArticlesStockList);

ArticlesStock类中,我有道具名称Producer一个字符串

如何在ComboBox中将其设置为我的路径? 通常我们可以用道具设置它。但在这里我有一个列表。在里面,我还有一个列表。在此列表中,必须设置第一项值。 C#转换如何将其设置为显示成员

((List<ArticlesStock>)Example[0])[0].WarehouseDeliveryNoteItem.Producer;

1 个答案:

答案 0 :(得分:2)

我将执行以下操作:为组合框的项目定义一个DataTemplate,然后使用转换器检索所需的属性。

DataTemplate定义:

<ComboBox ItemsSource="{Binding Example}">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="{x:Type List}">
            <!--no Path is specified, which is equivalent to Path="."-->
            <TextBlock Text="{Binding Converter={StaticResource MyConv}}"></TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

以及用于访问Producer属性的转换器:

public class MyConv : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // here value will be an item of Example list, so a List<ArticlesStock>
        var val = value as List<ArticlesStock>;
        return val[0].Producer;
    }
}

请注意,为简洁起见,我简化了模型结构。