Reputation: 127
I am trying to retrieve items at specific index locations from an ObservableCollection. According to MSDN, there are properties Item
and Items
.
private ObservableCollection<string> _strings = new ObservableCollection<string>();
string item1;
item1 _strings.Item[0];
item1 _strings.Items[0];
When I use Item
, I get:
'System.Collections.ObjectModel.ObservableCollection' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Collections.ObjectModel.ObservableCollection' could be found (are you missing a using directive or an assembly reference?)
And when I use Items
, I get:
Cannot access protected member 'System.Collections.ObjectModel.Collection.Items' via a qualifier of type 'System.Collections.ObjectModel.ObservableCollection'; the qualifier must be of type 'Model.MyStringCollection' (or derived from it)
I just cannot see what I am doing wrong here, right now.
Upvotes: 1
Views: 2893
Reputation: 10708
When any class has an indexed property it gets labeled as and Item
property. This allows referencing the indexer property with object[index]
syntax, not object.Item[index]
syntax. This is due to the fact that the property needs a name, and is a property defined as
public T this[int index]
{
get
{
//...
}
set
{
//...
}
}
EDIT: See this article on indexer properties for further reading
Upvotes: 1
Reputation: 6553
You just call it like:
private ObservableCollection<string> _strings = new ObservableCollection<string>();
...
string item1 = _strings[0];
But you need to add to the collection first!
Upvotes: 3
Reputation: 5131
The right syntax is this:
_strings.Item(0);
not this
_strings.Item[0];
The call to Item()
or Items()
is actually a method call. The indexer operator is not needed.
Upvotes: -2