简体   繁体   English

如何在ViewModel中使用来自后面代码的对象

[英]How to use an object in ViewModel coming from code behind

I have a set of pages between which I navigate and between which I need to pass some parameters, namely some objects of the type of my Models. 我有一组页面,在这些页面之间进行导航,并在这些页面之间传递一些参数,即模型类型的某些对象。 When I navigate to a page I Setup this new page's constructor with a parameter of the type of the object I need, so the class is implemented as follows: 当我导航到页面时,使用需要的对象类型的参数来设置此新页面的构造函数,因此该类的实现如下:

public partial class ArtigoEdit : ContentPage
{
    EditionsViewModel viewModel;
    public ArtigoEdit(Models.Artigo artigo)
    {
        InitializeComponent();

        BindingContext = viewModel = new EditionsViewModel();

        this.viewModel.Artigo = artigo;
    }
}

As you can see I'm also using the MVVM pattern and on its side I have a variable "Artigo" to which I want to assign the object my constructor receives: 如您所见,我也在使用MVVM模式,在它的一边,我有一个变量“ Artigo”,我想为其分配构造函数接收到的对象:

Models.Artigo artigo;
public Models.Artigo Artigo
{
    get { return artigo; }
    set { artigo = value; this.Notify("Artigo"); }
}

The problem is that if I try to access the attributes of this object in order to change the way they are displayed and bind to these new variables instead the object is null when the page opens so the variables are not shown: 问题是,如果我尝试访问此对象的属性以更改它们的显示方式并绑定到这些新变量,则在页面打开时该对象为null,因此不显示变量:

string tipoArtigo = "";
public string TipoArtigo
{
    get { return tipoArtigo; }
    set 
    { 
        if (Artigo != null)
        {
            if(Artigo.TipoArtigo == "P")
                tipoArtigo = "Produto";
            else if (Artigo.TipoArtigo == "S")
                tipoArtigo = "Serviço";
            else if (Artigo.TipoArtigo == "O")
                tipoArtigo = "Outro";
            else if (Artigo.TipoArtigo == "I")
                tipoArtigo = "Imposto";
            else
                tipoArtigo = value;
        }
        this.Notify("TipoArtigo"); 
    }
}

Is this not the correct way of doing this? 这不是正确的方法吗? If not, what is my alternative? 如果没有,我有什么选择? Beware that my ViewModels all implemente a ViewModelBase class that itself implements INotifyPropertyChanged so do not worry about that! 请注意,我的ViewModels都实现了一个ViewModelBase类,该类本身实现了INotifyPropertyChanged因此不必担心! :) :)

Silly me, I'm sorry for disturbing and I thank to all the people who tried to help. 愚蠢的我,很抱歉打扰您,也感谢所有尝试提供帮助的人。 What was happening was: I was binding these variables to an Entry, but for some reason it was not expanding to fit the size of information so although it was there it did not appear to be...luckily I've noticed it. 发生的事情是:我将这些变量绑定到一个Entry,但是由于某种原因,它没有扩展到适合信息的大小,因此尽管它在那里,但似乎并没有...幸运的是,我注意到了它。

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

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