如何在wpf mvvm中将属性值传递给另一个类的属性 [英] how to pass property value to property of another class in wpf mvvm
问题描述
我想将SecondViewModel SecondProperty 的值传递给ViewModel myProperty ,并在 TextBlock 上显示该值. 我想在SecondViewModel中完成编码. 希望一切都清楚.
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.
感谢Advance的帮助.
Thanks for the help in Advance.
查看:
<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"); }
}
推荐答案
根据您的评论,假设ViewModel
持有SecondViewModel
个项目的集合,则需要为SecondViewModel
的每个实例设置PropertyChangedEvent
触发ViewModel.myProperty
刷新.例如...
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));
}
}
顺便说一句,永远不要使用魔术字符串"调用OnPropertyChanged()
-改用nameof()
.
As an aside, you should never call OnPropertyChanged()
with a "magic string" - use nameof()
instead.
这篇关于如何在wpf mvvm中将属性值传递给另一个类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!