【发布时间】:2014-11-20 14:11:18
【问题描述】:
我想创建一个自定义ObservableCollection<string> 以在 WPF 中与 MVVM 一起使用。我的实际目标是通过两个属性来扩展标准ObservableCollection<string>,它们返回选定的索引和选定的项目,以及通过检查给定字符串是否在集合中的方法。目前看起来是这样的:
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>,但标准方法,如Add、Clear 等,将不起作用。当然,那是因为我每次创建 MyStringCollection 的实例时都会创建一个单独的实例_strings。
我的问题是如何在不手动添加这些功能的情况下向/从我的 ObservableCollection<string>() 添加/清除元素?
【问题讨论】:
-
仅供参考,如果您可以使用 LINQ,则无需定义自己的
Contains方法。只需添加using System.Linq;,您就可以在ObservableCollection<T>上使用IEnumerable 扩展方法Contains。 msdn.microsoft.com/en-us/library/…
标签: c# mvvm observablecollection