代码之家  ›  专栏  ›  技术社区  ›  Marks

在UserControl的ViewModel中处理DependencyProperty更改

  •  0
  • Marks  · 技术社区  · 15 年前

    我现在正在尝试让我的第一个wpfusercontrol工作。它由一些UI元素和一个ViewModel组成,保存数据并执行工作。它有一个项目列表作为输入,另一个项目列表作为输出。当绑定到输入的列表更改时,我需要在ViewModel中完成某个任务。但是我找不到一个方法在这个列表发生变化时运行一个方法。

    我认为最好的方法是为输入和输出列表提供两个dependencProperties。如果输出列表发生更改,则应该通知绑定对象,因为它已注册为DependencyProperty。我想使用DependencyPropertyChanged委托在ViewModel中指定在输入更改时执行的方法。

    public List<AClass> Input
        {
            get { return (List<AClass>)GetValue(InputProperty); }
            set { SetValue(InputProperty, value); }
        }
    public static readonly DependencyProperty InputProperty =
            DependencyProperty.Register("Input", typeof(List<AClass>), typeof(MyUserControl), new UIPropertyMetadata(new List<AClass>(),CallBackDelegate));
    

    我尝试了不同的方法来设置viewmodel构造函数中的委托,但是它们都不起作用。如何在viewmodel中指定在输入列表更改时执行的方法?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Wonko the Sane    15 年前

    我将使用ObservableCollections,而不是DependencyProperty中的列表。这会给你“自动”通知,等等。下面是我脑子里想不出来的可能不太完整的伪代码,让你开始:

    视图模型

    using System.Collections.ObjectModel;
    
    namespace MyNamespace;
    
    class MyViewModel
    {
        ObservableCollection<AClass> mInput = new ObservableCollection<AClass>();
        ObservableCollection<AClass> mOutput = new ObservableCollection<AClass>();
    
        public MyViewModel()
        {
            mInput.CollectionChanged += 
                new NotifyCollectionChangedEventHandler(mInput_CollectionChanged);
        }
    
        void mInput_CollectionChanged(object sender, 
                                      NotifyCollectionChangedEventArgs e)
        {
            DoSomething();    
        }
    
        public ObservableCollection<AClass> Input
        {
            get { return mInput; }
        }
    
        public ObservableCollection<AClass> Output
        {
            get { return mOutput; }
        }
    }
    

    在控制/视野中的某处

    <ItemsControl ItemsSource="{Binding Input}">
        <!-- Rest of control design goes here -->
    </ItemsControl>
    
    <ItemsControl ItemsSource="{Binding Output}">
        <!-- Rest of control design goes here -->
    </ItemsControl>
    

    class MyViewOrControl
    {
        // ViewModel member
        private readonly MyViewModel mViewModel = new MyViewModel();
    
        // Constructor
        public MyViewOrControl()
        {
            InitializeComponent();
            this.DataContext = mViewModel;
        }
    
        // Property (if needed)
        public ViewModel
        {
            get { return mViewModel; }
        }
    }