简体   繁体   中英

Dynamically selecting entity properties?

I'll try to explain the situation as it is:

I have a WPF application which I used the MVVM pattern for. So the code is divided in at least three 'layers'. Now, the GUI is dynamically constructed by customizable definitions placed in an external XML file. So for example, in that XML file each row of a Grid and it's meaning and layout is defined. As well as the column it should read from a table in the data source. By the way, that data source is implemented in my application using Entity Framework.

Now, I haven't been able to find a way to dynamically select a property from an entity. For example:

Binding bnd = new Binding();
bnd.Source = from i in DataModel.Entities.machine
             where i.name == Properties.Settings.Default.CurrentMachine
             select i.<<THE COLUMN DEFINED IN THE XML>>

so I'm looking for a way to convert a string (taken from the XML) to an actual property of the entity.

Can this be done? If so, how exactly?

Thanks a lot!

Try using reflection and the GetProperty() method.

    public Binding ReflectionBinder(string propertyName)
    {
        var binding = new Binding();
        var src = (from i in DataModel.Entities.machine
                   where i.name == Properties.Settings.Default.CurrentMachine
                   select i);

        binding.Source = src.GetType().GetProperty(propertyName).GetValue(src, null);

        return binding;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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