I want to create a custom ObservableCollection<string>
to use with MVVM in WPF. My actual goal is to extend the standard ObservableCollection<string>
by two properties, which return the selected index and the selected item, as well as by a method that checks whether a given string is in the Collection. It currently looks like this:
public class MyStringCollection : ObservableCollection<string>
{
private int _selectedIndex;
private ObservableCollection<string> _strings;
public MyStringCollection() : base()
{
_selectedIndex = 0;
_strings = new ObservableCollection<string>();
}
/// <summary>
/// Index selected by the user
/// </summary>
public int SelectedIndex
{
get { return _selectedIndex; }
set { _selectedIndex = value; }
}
/// <summary>
/// Item selected by the user
/// </summary>
public string Selected
{
get { return _strings[SelectedIndex]; }
}
/// <summary>
/// Check if MyStringCollection contains the specified string
/// </summary>
/// <param name="str">The specified string to check</param>
/// <returns></returns>
public bool Contains(string str)
{
return (_strings.Any(c => (String.Compare(str, c) == 0)));
}
}
Even though MyStringCollection
inherits from ObservableCollection<string>
, the standard methods, such as Add
, Clear
, etc., won't work. Of course, that is because I create a separate instance _strings
each time I create an instance of MyStringCollection.
My question is how to add/clear elements to/from my ObservableCollection<string>()
without adding those functions manually?