how to pass property value to property of another class in wpf mvvm

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 21:44:20

问题


I want to pass SecondViewModel SecondProperty value to ViewModel myProperty and show the value on TextBlock. i want the coding to be done in SecondViewModel. Hope it is clear.

Thanks for the help in Advance.

View:

<TextBlock Text="{Binding Path=myProperty}"/>

ViewModel:

private int _myProperty;
public int myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; OnPropertyChanged("myProperty"); }
}

SecondViewModel:

private int _secondProperty;
public int SecondProperty
{
   get { return _secondProperty; }
   set { _secondProperty = value; OnPropertyChanged("SecondProperty"); }
}

回答1:


From your comment, assuming that ViewModel holds a collection of SecondViewModel items, you need to set the PropertyChangedEvent for each instance of SecondViewModel to trigger ViewModel.myProperty to refresh. e.g. ...

public class ViewModel
{
    private List<SecondViewModel> _secondViewModels = new List<SecondViewModel>();

    public IEnumerable<SecondViewModel> SecondViewModels => _secondViewModels;

    public int myProperty => _secondViewModels.Sum(vm => vm.SecondProperty);

    public void AddSecondViewModel(SecondViewModel vm)
    {
        _secondViewModels.Add(vm);
        vm.PropertyChanged += (s, e) => OnPropertyChanged(nameof(myProperty));
        OnPropertyChanged(nameof(myProperty));
    }
}

As an aside, you should never call OnPropertyChanged() with a "magic string" - use nameof() instead.




回答2:


If you need that, you should create a VM DataSource to create a dependency in your first VM.

public class YourViewModelDataSource
 {

private ViewModel viewModel;
private SecondViewModel secondViewModel;

public YourViewModelDataSource(ViewModel viewModel, SecondViewModel secondViewModel)
    {
      this.viewModel = viewModel;
      this.secondViewModel = secondViewModel;
    }

public void CreateDataSource()
    {
      this.secondViewModel.PropertyChanged += this.OnSecondViewModelPropertyChanged;
    }

private void OnSecondViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                //As pointed in comments, you need to have the second property in your first ViewModel then do this.
                case "SecondProperty":
                    this.viewModel.myProperty = this.secondViewModel.SecondProperty;
                    break;
            }
        }
  }

When you create your VMs then use this class to create the dependency. Every time SecondViewModel SecondProperty changes, the ViewModel myProperty will be raised. I hope it's clear, let me know if you need something else



来源:https://stackoverflow.com/questions/52854751/how-to-pass-property-value-to-property-of-another-class-in-wpf-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!