如何让一个viewmodel更新另一个viewmodel上的属性?

时间:2011-02-26 16:44:23

标签: c# events mvvm delegates view

我需要一个简单的例子来说明如何让一个viewmodel更新另一个viewmodel上的属性。

这是'情况。我有一个视图和viewmodel负责显示一个专辑列表。我有另一个视图和viewmodel负责添加新专辑(几个文本框和一个按钮)现在添加新专辑如何告诉另一个视图中的Collection已添加新专辑? 我读到了可以为我做这个的框架,但我试图学习所以我不会使用框架来存在...

4 个答案:

答案 0 :(得分:3)

这里有一些拼图,取自Josh Smith's classic demo app,显示了如何使用事件来支持mvvm提供的可测试性和松散情侣

数据

这不是cource的视图模型,但是大多数有趣的应用程序都有数据和数据。它必须来自某个地方!这是一个显而易见的候选人,可以在添加新项目时举行活动:

public class CustomerRepository
{
    ...

    /// <summary>Raised when a customer is placed into the repository.</summary>
    public event EventHandler<CustomerAddedEventArgs> CustomerAdded;

    /// <summary>
    /// Places the specified customer into the repository.
    /// If the customer is already in the repository, an
    /// exception is not thrown.
    /// </summary>
    public void AddCustomer(Customer customer)
    {
        if (customer == null) throw new ArgumentNullException("customer");
        if (_customers.Contains(customer)) return;

        _customers.Add(customer);

        if (CustomerAdded != null)
            CustomerAdded(this, new CustomerAddedEventArgs(customer));
    }

    ...
}

外壳

考虑使用可能通过管理工作空间来协调给定演示文稿的视图模型。有些人可能称之为经理(yuk!)或MainViewModel。我喜欢ShellViewModel。此视图模型具有创建新项目的命令:

public class MainWindowViewModel : WorkspaceViewModel
{

    readonly CustomerRepository _customerRepository;

    public MainWindowViewModel(...)
    {
        _customerRepository = new CustomerRepository(customerDataFile);
    }

    void _createNewCustomer()
    {
        var newCustomer = Customer.CreateNewCustomer();
        var workspace = new CustomerViewModel(newCustomer, _customerRepository);
        Workspaces.Add(workspace);
        _setActiveWorkspace(workspace);
    }

    ObservableCollection<WorkspaceViewModel> _workspaces;

    void _setActiveWorkspace(WorkspaceViewModel workspace)
    {
        var collectionView = CollectionViewSource.GetDefaultView(Workspaces);
        if (collectionView != null)
            collectionView.MoveCurrentTo(workspace);
    }

 }

模型对象

您是否注意到静态工厂构造函数方法(Customer.CreateNewCustomer)?它清楚地说明了它的目的是什么,并提供了一个封装创建新客户所涉及的任何复杂性的机会。

模型对象ViewModel包装器

这通常源于使INPC通知易于使用的基类,因为它是数据绑定的基础。请注意,Email属性是直接传递给模型对象的email属性,但DisplayNAme纯粹是UI驱动的。在添加新项目的情况下,它恰当地说......“新Cistomer”:

public class CustomerViewModel : WorkspaceViewModel, IDataErrorInfo
{

    public CustomerViewModel(Customer customer, CustomerRepository customerRepository)
    {
        if (customer == null) throw new ArgumentNullException("customer");
        if (customerRepository == null) throw new ArgumentNullException("customerRepository");

        _customer = customer;
        _customerRepository = customerRepository;
     }

    readonly Customer _customer;

    public string Email
    {
        get { return _customer.Email; }
        set
        {
            if (value == _customer.Email) return;

            _customer.Email = value;
            base.OnPropertyChanged("Email");
        }
    }

    public override string DisplayName
    {
        get {
            if (IsNewCustomer)
            {
                return Strings.CustomerViewModel_DisplayName;
            }
            ...

            return String.Format("{0}, {1}", _customer.LastName, _customer.FirstName);
        }
    }


    #region Save Command

    /// <summary>
    /// Returns a command that saves the customer.
    /// </summary>
    public ICommand SaveCommand
    {
        get
        {
            return _saveCommand ??
                   (_saveCommand = new RelayCommand(param => _save(), param => _canSave));
        }
    }
    RelayCommand _saveCommand;

    /// <summary>
    /// Returns true if the customer is valid and can be saved.
    /// </summary>
    bool _canSave
    {
        get { return String.IsNullOrEmpty(_validateCustomerType()) && _customer.IsValid; }
    }

    /// <summary>
    /// Saves the customer to the repository.  This method is invoked by the SaveCommand.
    /// </summary>
    void _save()
    {
        if (!_customer.IsValid)
            throw new InvalidOperationException(Strings.CustomerViewModel_Exception_CannotSave);

        if (IsNewCustomer)
            _customerRepository.AddCustomer(_customer);
        base.OnPropertyChanged("DisplayName");
    }

}

ViewModel的ViewModel集合

这可能支持过滤,排序,求和。在添加新客户的情况下,请注意它正在订阅我们添加到存储库的事件。另请注意,它使用了ObservableCollection,因为它内置了对数据绑定的支持。

public class AllCustomersViewModel : WorkspaceViewModel
{

    public AllCustomersViewModel(CustomerRepository customerRepository)
    {
        if (customerRepository == null) throw new ArgumentNullException("customerRepository");

        _customerRepository = customerRepository;

        // Subscribe for notifications of when a new customer is saved.
        _customerRepository.CustomerAdded += OnCustomerAddedToRepository;

        // Populate the AllCustomers collection with CustomerViewModels.
        _createAllCustomers();              
    }

    /// <summary>
    /// Returns a collection of all the CustomerViewModel objects.
    /// </summary>
    public ObservableCollection<CustomerViewModel> AllCustomers
    {
        get { return _allCustomers; }
    }
    private ObservableCollection<CustomerViewModel> _allCustomers;

    void _createAllCustomers()
    {
        var all = _customerRepository
            .GetCustomers()
            .Select(cust => new CustomerViewModel(cust, _customerRepository))
            .ToList();

        foreach (var cvm in all)
            cvm.PropertyChanged += OnCustomerViewModelPropertyChanged;

        _allCustomers = new ObservableCollection<CustomerViewModel>(all);
        _allCustomers.CollectionChanged += OnCollectionChanged;
    }

    void OnCustomerViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        const string IsSelected = "IsSelected";

        // Make sure that the property name we're referencing is valid.
        // This is a debugging technique, and does not execute in a Release build.
        (sender as CustomerViewModel).VerifyPropertyName(IsSelected);

        // When a customer is selected or unselected, we must let the
        // world know that the TotalSelectedSales property has changed,
        // so that it will be queried again for a new value.
        if (e.PropertyName == IsSelected)
            OnPropertyChanged("TotalSelectedSales");
    }

    readonly CustomerRepository _customerRepository;

    void OnCustomerAddedToRepository(object sender, CustomerAddedEventArgs e)
    {
        var viewModel = new CustomerViewModel(e.NewCustomer, _customerRepository);
        _allCustomers.Add(viewModel);
    }

}

查看完整文章并下载代码!

HTH,
Berryl

答案 1 :(得分:1)

有几种方法:

1)AlbumsVM知道CreateAlbumVM(例如,首先打开第二个)。在这种情况下,您只需使用AlbumsVM提供的详细信息将相册添加到CreateAlbumVM即可 2)CreateAlbumVM知道AlbumsVM。然后它可以将专辑插入AlbumsVM本身 3)AlbumsVM从某个地方收到ObservableCollection的专辑。然后,CreateAlbumVM可以将新相册插入原始ObservableCollection,这将反映在AlbumsVM中 4)这些viewModel之间有一些中介提供事件AlbumWasAdded

答案 2 :(得分:0)

只需实现这样的属性即可。

private bool _checked;
    public bool Checked
    {
        get { return _checked; }
        set
        {
            if (value != _checked)
            {
                _checked = value;
                OnPropertyChanged("Checked");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyCHanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

然后将您的其他viewmodel订阅到propertyChangedEvent并执行您需要执行的操作。 确保您的ViewModel实现INotifyPropertyChanged

答案 3 :(得分:0)

您给人的印象是您认为每个View的Viewmodel都应该是隔离的类。他们不是。 Viewmodels以View可以绑定它的方式重新打包底层数据。因此,制作一个ObservableCollection <Album&gt;并让两个Viewmodels引用它。完成!