简体   繁体   English

如果值在另一类中更改,则如何在一个类中更改值

[英]How to change value in one class if value changes in another

Let's say I have a parameter in my ViewModel: 假设我的ViewModel中有一个参数:

public string ChosenQualityParameter
{
     get => DefectModel.SelectedQualDefectParameters?.Name ?? "Не выбран параметр";
}

and I have a class DefectModel with parameter SelectedQualDefectParameters.Name in it. 我有一个带有参数SelectedQualDefectParameters.Name DefectModel类。 I want to change the UI binded to ChosenQualityParameter , when the Name parameter changes too. Name参数也更改时,我想更改绑定到ChosenQualityParameter的UI。 But I don't know how to do this properly. 但是我不知道该怎么做。 Any suggestions? 有什么建议么? Thanks in advance. 提前致谢。

You might define your ViewModel class like this: 您可以这样定义ViewModel类:

public class ViewModel
{
    private DefectModel _defectModel;

    public ViewModel(DefectModel defectModel)
    {
        _defectModel = defectModel;
    }

    public string ChosenQualityParameter
    {
        get => _defectModel.SelectedQualDefectParameters?.Name ?? "Не выбран параметр";
    }
}

I personally do not like such dependencies in viewmodels, but it might get the job done here. 我个人不喜欢视图模型中的此类依赖关系,但可以在这里完成工作。 It seems to work in a console application anyway: 无论如何,它似乎可以在控制台应用程序中工作:

using System;

public class Parameters
{
    public string Name { get; set; }
}

public class DefectModel
{
    public Parameters SelectedQualDefectParameters { get; set; }
}

public class ViewModel
{
    private DefectModel _defectModel;

    public ViewModel(DefectModel defectModel)
    {
        _defectModel = defectModel;
    }

    public string ChosenQualityParameter
    {
        get => _defectModel.SelectedQualDefectParameters?.Name ?? "Не выбран параметр";
    }
}

class Program
{
    static void Main()
    {
        var defectModel = new DefectModel
        {
            SelectedQualDefectParameters = new Parameters
            {
                Name = "test"
            }
        };

        var viewModel = new ViewModel(defectModel);

        Console.WriteLine(viewModel.ChosenQualityParameter);

        defectModel.SelectedQualDefectParameters.Name = "changed";

        Console.WriteLine(viewModel.ChosenQualityParameter);

        Console.ReadKey();
    }
}

Thanks to @Knoop and @BartHofland, I've solved my issue by using INotifyPropertyChanged in my DefectModel and SelectedQualDefectParameters classes. 感谢@Knoop和@BartHofland,我通过在DefectModelSelectedQualDefectParameters类中使用INotifyPropertyChanged解决了我的问题。 For setting ChosenQualityParameter I used MessagingCenter to send new value. 为了设置ChosenQualityParameter我使用MessagingCenter发送新值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM