2

In a WPF MVVM(Caliburn Micro) application I have a empty ViewModel and a empty View. (The view model doesn't have any properties, and view doesn't have any fields.)

CommonView (CommonView.cs)

CommonViewModel (CommonView.xaml - UserControl)

There is a need to add properties and fields dynamically to the view and ViewmModel.

I have a list of properties in a PropertyInfo object. Based on the PropertyInfo I need to add properties to the ViewModel dynamically during Runtime.

  1. Is It Possible? Can any one explain this with some code sample?
  2. Is it possible to implement INotifyPropertyChange to dynamically added properties?

UPDATE:

I have a Model class as well, where I have properties. Few of them are decorated with custom attribute.

By using reflection I can get properties (PropertyInfo) which has decorated with custom attribute. Ex:

var props = t.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(CustomAttribute)));

Now I want to add those properties to ViewModel during the runtime. This is the actual requirement.

Ex:

public class CommonViewModel: Screen
{ 
   //Below properties needs to be added dynamically during the runtime
   Public string Prop1{get;set;}
   Public string Prop2{get;set;}
   Public string Prop3{get;set;}
}
Community
  • 1
  • 1
Rahul
  • 2,431
  • 3
  • 35
  • 77
  • @MikyD Could you please just explain how can I add properties dynamically with INotifyPropertyChange implementation? – Rahul Feb 02 '17 at 05:33
  • By generating code at runtime either with [.NET CodeDOM](http://stackoverflow.com/a/826435/585968) or Reflection Emit, though the former is waaaay easier –  Feb 02 '17 at 07:13
  • This is possible, it's just very hard to accomplish. There is actually something in the framework which does this--the ModelItem used in WF4 https://blogs.msdn.microsoft.com/tilovell/2011/04/11/wf4-modelitem-modelitemimpl-and-icustomtypedescriptor/ It's designed to wrap a poco object and provide for facilities needed in the UI, such as undo/redo and attaching properties (I might be misremembering that last one). If you look into its implementation you can figure out how it works and how Bindings use its interfaces to perform binding tasks. –  Feb 02 '17 at 15:39
  • @Rahul: Either user jannagy02's solution, or take a look at [CustomTypeDescriptor](https://msdn.microsoft.com/en-us/library/system.componentmodel.customtypedescriptor(v=vs.110).aspx) and [TypeDescriptorProvider](https://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptionprovider(v=vs.110).aspx) . Custom type descriptor basically allows you to describe properties at runtime and it works with WPF binding. For example, you can use it with some kind of PropertyGrid that autogenerates the grid. – Liero Feb 02 '17 at 15:46

0 Answers0