首页 文章

如何设置ItemSource和ItemTemplate以显示对象列表

提问于
浏览
0

我有一个列表框,我想显示一个对象列表,我遵循MVVM模式,并发现很难实现我想要的 .

MainWindowView.xaml

<ListBox ItemsSource="{Binding Path=MyList}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Path=Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

MainWindowViewModel.cs

private List<ListBoxItem> _myList = new List<ListBoxItem>();

    public List<ListBoxItem> MyList
    {
        get { return _myList ; }
        set
        {
            _myList = value;
            OnPropertyChanged("MyList");
        }
    }

    public SprintBacklogViewModel()
    {
        foreach(MyObject obj in MyObjects.MyObjectList)
        {
            ListBoxItem item = new ListBoxItem();
            item.Content = obj;
            MyList.Add(item);
        }
    }

MyList正在更新,但窗口中没有显示任何内容 . (ItemsSource = ""也有效,我用不同的数据测试过)我之前没有使用过ItemTemplate,所以任何指针都是受欢迎的 . 我对它的理解是,如果我正确设置它将在我的对象中显示数据 . 例如:

<Label Content="{Binding Path=Name}"/>

MyObject中有一个名为Name的属性,我想在列表中将其显示为标签

*编辑在我的窗口中,我得到一行文本 - mynamespace.MyObject

2 回答

  • 1

    ViewModel中的MyList属性是ListBoxItem类型的属性,它具有Name属性,但它不是MyObject的名称 . 因此,您需要在ViewModel中更改您的属性

    Replace

    private List<ListBoxItem> _myList = new List<ListBoxItem>();
    
    public List<ListBoxItem> MyList
    {
        get { return _myList ; }
        set
        {
            _myList = value;
            OnPropertyChanged("MyList");
        }
    }
    

    with

    private List<MyObject> _myList = new List<MyObject>();
    
    public List<MyObject> MyList
    {
        get { return _myList ; }
        set
        {
            _myList = value;
            OnPropertyChanged("MyList");
        }
    }
    
  • 1
    • 您的列表不应包含UI元素而是数据(您是 data -binding),如果绑定到 ListBoxItems 列表 ListBox 将忽略 ItemTemplate 并只使用项目,因为它们适合 ListBox 的预期容器 . 容器将自动生成,您无需在列表中执行此操作 .

    • 如果在运行时向项目集添加项目,则需要通知绑定引擎更新更改,为此应使用ObservableCollection或任何实现INotifyCollectionChanged的项目 . (这样做时你通常会进一步创建字段 readonly 并且只提供一个getter)这就是为什么没有项目的原因 .

相关问题