TNA
TNA

Reputation: 616

return list of class object in WPF

I have a class as below.

namespace WpfApplication2
{
    class TaskItem
    {
        private string name;
        private string item;
        private string description;
        private int priority;
        public string Name
        {
            get
            { return name; }
            set
            { this.name = value; }
        }

        public string Item
        {
            get
            {
                return item;
            }
            set
            {
                this.item = value;
            }
        }
        public string Description
        {
            get
            {
                return String.Format("{0} {1}",name,item);
            }
        }
        public int Priority
        {
            get
            {
                return priority;
            }
            set
            {
                this.priority = value;
            }
        }

        public TaskItem()
        {


        }

    }
}

I want to return the list of this class object to my wpf application as below.

<WpfApplication2:TaskItem x:Key="taskItem"/>

After that I will bind this to ListBox. How could I return this list of class object? Please advise. Thanks.

Upvotes: 1

Views: 1424

Answers (3)

Brent Stewart
Brent Stewart

Reputation: 1840

Your xaml declaration is for a single TaskItem, not a collection. You need a collection to bind to the ItemsSource of your ListBox. See the notes on msdn about the limitations of a xaml only solution using ObservableCollection. You will probably want to create a list in code to bind to the ListBox, or create your own class that inherits from ObservableCollection and then create an instance of that class in you xaml instead.

Upvotes: 1

Gishu
Gishu

Reputation: 136633

Technically possible.. with something similar to this (Replace Observable collection with List and my:Person with your custom class). See also: Generics support was added recently to XAML

<Window>
    <Window.DataContext>
        <ObservableCollection x:TypeArguments="my:Person">
            <my:Person FirstName="Tom" LastName="Holiday" />
            <my:Person FirstName="Joan" LastName="Holiday" />
        </ObservableCollection>
    </Window.DataContext>
    …
</Window>

Upvotes: 0

Pacman
Pacman

Reputation: 2245

Have you tried to create a List<TaskItems> and set this as the DataContext ?

Upvotes: 0

Related Questions