Search code examples
c#objectmvvmdevexpressbindinglist

How to access object's property in inside other object's property?


//class MessageModel
public class MessageModel
{
    public string Name{get;set;}
    public BindingList<AttachDocument> _attachDocument {get;set;};
}
// class AttachDocument that it's object is a MessageModel property
public class AttachDocument
{
    public string AttachName { get; set; }
    public bool IsCheck { get; set; }
}

MessageModel source = new MessageModel { AttachDocument = new BindingList<AttachDocument>()};
MessageModel value = new MessageModel { AttachDocument = new BindingList<AttachDocument>()};
// Error "AttachName" is not defined
source.AttachDocument.AttachName = value.AttachDocument.AttachName; // What I want to access

So how can I access access object's property in inside other object's property and assign a value.


Solution

  • There is no property with the name AttachDocument. It is a class that is unrelated to the field you are having defined. There are a few issues you need to address:

    • First, you need to make the field public, to make it accessible outside of your class;
    • Second, you need to make it a property to follow conventions, and help binding it in WPF for example;
    • Third, the list should be addressed by index, but only after you have added an item to it.

    Since you want to iterate over the list, you need something like a foreach:

    public class MessageModel
    {
        public string Name{get;set;}
        public BindingList<AttachDocument> AttachDocuments {get;set;}
    }
    
    foreach (AttachDocument s in source.AttachDocuments)
    {
        AttachDocument t = new AttachDocument();
        t.AttachName = s.AttachName;
    
        value.AttachDocuments.Add(t);
    }