【问题标题】:how to pass property value to property of another class in wpf mvvm如何将属性值传递给wpf mvvm中另一个类的属性
【发布时间】:2018-10-17 12:20:09
【问题描述】:

我想将 SecondViewModel SecondProperty 值传递给 ViewModel myProperty 并在 TextBlock 上显示该值。 我希望在 SecondViewModel 中完成编码。 希望清楚。

感谢您提前提供的帮助。

查看:

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

视图模型:

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"); }
}

【问题讨论】:

  • 为什么单个视图需要 2 个视图模型?这没有任何意义。
  • 其实说得通。例如,DataGrid 应该有一个 ObservableCollection&lt;OtherVM&gt;,所以这并不奇怪。
  • 我有 2 个视图和 2 个视图模型,当第一个视图文本框更新时,我想在第二个视图文本块上显示它

标签: c# wpf mvvm inotifypropertychanged


【解决方案1】:

根据您的评论,假设ViewModel 拥有SecondViewModel 项的集合,您需要为SecondViewModel 的每个实例设置PropertyChangedEvent 以触发ViewModel.myProperty 刷新。例如...

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()

【讨论】:

    【解决方案2】:

    如果需要,您应该创建一个 VM 数据源以在您的第一个 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;
                }
            }
      }
    

    当你创建你的虚拟机时,然后使用这个类来创建依赖。每次SecondViewModel SecondProperty 更改时,ViewModel myProperty 都会被提升。我希望它很清楚,如果您需要其他内容,请告诉我

    【讨论】:

    • 检查我的编辑。顺便说一句,不要在你的 SecondViewModel 中尝试应用 SOLID :) 创建一个具有该职责的新类
    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2017-02-28
    • 2018-08-11
    • 1970-01-01
    • 2013-08-14
    相关资源
    最近更新 更多