How to add Properties to a ViewModel Class Dynamically in Runtime in C# MVVM

拜拜、爱过 提交于 2019-12-08 12:02:04

问题


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;}
}

来源:https://stackoverflow.com/questions/41994696/how-to-add-properties-to-a-viewmodel-class-dynamically-in-runtime-in-c-sharp-mvv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!