Is it possible to get the type of object and dynamically set it as the object. I have several ViewModels that all contain the same Property and want to do something like this
if (this.DataContext is CamerasViewModel)
{
//Type type = Type.GetType((this.DataContext.ToString());
object o = Assembly.GetExecutingAssembly().CreateInstance(this.DataContext.GetType().ToString());
Type type = o.GetType();
foreach (ButtonViewModel button in (this.DataContext as type).Buttons)
{
if (button.DisplayName == this.Content.ToString())
{
this.Template = (ControlTemplate)this.FindResource(button.TemplateResource.Substring(0, button.TemplateResource.Length - 3) + "pr");
break;
}
}
}
Instead of saying this.DataContext as CamerasViewModel I want to say this.DataContext as THEDYNAMICTYPE
Any suggestions?
You’re probably much better taking all of your classes that have a
Buttonsproperty that you want to update the template on, and having them implement an interface. The interface would look something like this:and your view models would be declared something like this:
Then, in your if statement, instead of checking if the object is a CamerasViewModel, check if it’s an IHasButtons. Doing it this way is a lot safer than trying to determine at runtime if there’s a Buttons property on the object. You could get unlucky and run across a Buttons property that has the same name, but different functionality than you’re expecting. Then you’re back writing crazy logic to determine if this is REALLY the Buttons collection that you’re looking for. If you do it with interfaces, it’s extremely clear. If a ViewModel implements IHasButtons, then it’s a ViewModel you want to update. If it doesn’t implement IHasButtons, you’ll skip right over it