如何在wpf mvvm中将属性值传递给另一个类的属性 [英] how to pass property value to property of another class in wpf mvvm

查看:92
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆