Access MarkupControl properties from the view model

Hello,

I’ve managed to access the view model from the base type of the MC (MarkupControl) like so:

But how can I reverse this? To access the MC property (SelectedPageRoute) inside the view model code.
…My goal is to get rid of the OnInit() override and avoid it as much as possible in the future. This is because of this issue I’m facing: Web browser exception detailed page for custom thrown exceptions


Thanks

I don’t think it’s a good idea to make the ViewModel depend on the view, but you can find the control using something like Context.View.GetAllDescendants().OfType<MainMenyBase>().Where(c => c.DataContext == this).Single()

Why don’t you have SelectedPageRoute property in the view model if you need it there anyway? The control can then easily use the property.

You have a good point.

SelectedPageRoute is a DotvvmProperty of the MC. My situation is like this:


This is from a page (a .dothtml file) and mc prefix means MarkupControl (which is a trio of .dotcontrol, .cs for base type and .cs for view model).

If you try to tell me that a simpler way can be achieved, to make this SelectedPageRoute defined inside the view model but still available in the markup of the MC, please show me how. Now, it is declared inside the base type, in the standard way offered by the documentation on the DotVVM website, like so:

Sorry, I don’t see the entire context of the project, so my suggestion would be to add the SelectedPageRoute property to the view model, assigned somewhere when creating the instance.

class MainMenu
{
    public string SelectedPageRoute { get; set; };
}
...

new MainMenu { SelectedPageRoute = "MgmExamplePage" }

You can the use the property using a value binding in both the dothtml and dotcontrol files ({value: _this.SelectedPageRoute} or {value: _root.SelectedPageRoute}, since it seems to be a server-side constant, you can also use resource binding, but I digress)

If the MainMenuInstance is defined in a shared base view model and you are always setting the property to the current route, you can access it in Context.Route.RouteName.

Following your suggestion and doing some debug time exploration into Context.View I realized that SelectedPageRoute can be removed altogether and the main menu MC keeping all its integrity by just leveraging the existing view model property SelectedMenuItem. This approach greatly simplifying the code.

in the page markup:
image

in the MC view model:
image

in the MC Init():
image


Thank you, I consider this thread resolved.