我正在尝试实现一个可绑定的集合--一个专门的堆栈--它需要在我的Windows 8应用程序的一个页面上显示,并在发生任何更新时与之一起显示。为此,我实现了INotifyCollectionChanged和IEnumerable<>:
public class Stack : INotifyCollectionChanged, IEnumerable<Number>
{
...
public void Push(Number push)
{
lock (this)
{
this.impl.Add(push);
}
if (this.CollectionChanged != null)
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, push));
}
...and the equivalents for other methods...
#region INotifyCollectionChanged implementation
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion
public IEnumerator<Number> GetEnumerator()
{
List<Number> copy;
lock (this)
{
copy = new List<Number>(impl);
}
copy.Reverse();
foreach (Number num in copy)
{
yield return num;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}此集合类用于定义页面拥有的基础类实例的属性,该属性被设置为其DataContext (页面的计算器属性),然后绑定到GridView:
<GridView x:Name="StackGrid" ItemsSource="{Binding Stack, Mode=OneWay}" ItemContainerStyle="{StaticResource StackTileStyle}" SelectionMode="None">
... ItemTemplate omitted for length ...绑定最初在页面导航到时有效-堆栈中的现有项显示得很好,但添加到堆栈中的项/从堆栈中删除的项不会在GridView中反映出来,直到页面导航离开并返回。调试显示,堆栈中的CollectionChanged事件始终为空,因此在更新时从不调用它。
我遗漏了什么?
发布于 2013-10-26 15:43:05
就在刚才,我面临着同样的问题--自定义集合,我希望它是可绑定的。我发现只有从Collection<>派生的类才能绑定到。
为什么?现在我还不知道。因此,如果你真的想让它工作,那就从Collection<>派生出来,但这会扰乱你的设计。
https://stackoverflow.com/questions/15044458
复制相似问题