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

后端 未结 2 1991
南旧
南旧 2021-01-28 23:38

I want to pass SecondViewModel SecondProperty value to ViewModel myProperty and show the value on TextBlock. i want the codi

2条回答
  •  悲&欢浪女
    2021-01-29 00:23

    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 _secondViewModels = new List();
    
        public IEnumerable 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.

提交回复
热议问题