自定义ObservableCollection <string>以及其他函数</string>

时间:2014-11-20 14:11:19

标签: c# mvvm observablecollection

我想在WPF中创建一个与MVVM一起使用的自定义ObservableCollection<string>。我的实际目标是通过两个属性扩展标准ObservableCollection<string>,这两个属性返回选定的索引和选定的项目,以及检查给定字符串是否在Collection中的方法。它目前看起来像这样:

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)));
    }        
}

即使MyStringCollection继承自ObservableCollection<string>,标准方法(例如AddClear等)也无法正常工作。当然,这是因为我每次创建MyStringCollection实例时都会创建一个单独的实例_strings

我的问题是如何在不添加这些功能的情况下向/ ObservableCollection<string>()添加/清除元素?

2 个答案:

答案 0 :(得分:0)

您来自ObservableCollection<T>,因此this是对您的收藏的引用。你所需要的只是

public string Selected
{
    get { return this[SelectedIndex]; }
}

public bool Contains(string str)
{
    return (this.Any(c => (String.Compare(str, c) == 0)));
}        

请注意Contains() already exists as an extension method

答案 1 :(得分:0)

我不确定您要尝试实现的目标,但您不应该继承ObservableCollection<string>,更喜欢撰写而非继承即可。实际上你已经差不多完成了它(你已经有private ObservableCollection<string> _strings成员了。)

例如参见:Prefer composition over inheritance?

回到初始要求,如果您正在进行MVVM,很可能您希望公开两个 ObservableCollection<T> MyObjects属性和T MySelectedObject属性。

相关问题