【问题标题】:Creating extra presentation properties for ItemsSource items为 ItemsSource 项创建额外的表示属性
【发布时间】:2013-10-21 21:28:12
【问题描述】:

我有一个 ObservableCollection 项目绑定到列表框作为 ItemsSource。

其中一些项目也位于同一 ViewModel 上的另一个集合中(称为 CollectionTwo)。

我希望能够对 Collection2 中的项目进行计数,并将其显示为 CollectionOne 中的相应项目。当 CollectionTwo 属性发生变化(即 Count)时,也必须反映回 CollectionOne。

我猜想在 MVVM 中执行此操作的最佳方法是在 CollectionOne 中使用带有额外 Count 属性的 viewmodel 类包装项目。有人可以指出一个很好的例子吗?或者也许是解决这个问题的另一种方法,不会严重影响我的 ItemsSource 性能。

谢谢!

【问题讨论】:

    标签: c# wpf mvvm observablecollection inotifypropertychanged


    【解决方案1】:

    您可以使用继承来创建自定义集合...

    public class MyCollection<T> : ObservableCollection<T>, INotifyPropertyChanged
    {
        // implementation goes here...
        //
        private int _myCount;
        public int MyCount
        {
            [DebuggerStepThrough]
            get { return _myCount; }
            [DebuggerStepThrough]
            set
            {
                if (value != _myCount)
                {
                    _myCount = value;
                    OnPropertyChanged("MyCount");
                }
            }
        }
        #region INotifyPropertyChanged Implementation
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string name)
        {
            var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
        #endregion
    }
    

    这是一个包装 Observable Collection 并在其中放置自定义属性的类。该属性参与更改通知,但这取决于您的设计。

    要将其连接起来,您可以执行以下操作...

        public MyCollection<string> Collection1 { get; set; }
        public MyCollection<string> Collection2 { get; set; } 
        public void Initialise()
        {
            Collection1 = new MyCollection<string> { MyCount = 0 };
            Collection2 = new MyCollection<string> { MyCount = 0 };
            Collection2.CollectionChanged += (s, a) =>
                {
                    // do something here
                };
        }
    

    你也可以做类似...

    Collection1.PropertyChanged += // your delegate goes here
    

    【讨论】:

    • 太棒了!感谢您提供简洁的解决方案。很简单!
    • 你好@GarryVass,我现在才刚刚实现这个新包装的 ObservableCollection,但我认为它完全回答了我的问题。这不是用 MyCount 属性附加集合中的每个项目,对吗?而是将 one MyCount 属性添加到整个 Collection1 或 Collection2?因此,为集合中的每个项目添加附加属性的唯一方法是定义一个包装项目属性的附加类,添加一个附加的“视图状态”属性,然后我将其包装在常规的 ObservableCollection 中?
    • 是的,如果您需要附加到集合中的每个项目的附加属性。尽管如此,上述框架应该会有所帮助,如果您需要更新,请告诉我
    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 2014-07-09
    • 2014-01-11
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多