Search code examples
c#xamldata-bindingviewmodel

How do I get access to a content page's control from its view model that it was initially bound to?


What I'm looking to do is create and write all my methods in my view model file, and only place code in the code-behind file for functions that are automatically generated like SfDataGrid_SelectionChanged and other similar functions. So when I'm writting code in a view model file and if I need access to the page's control and its properties how do I get it? At this point, I have the BindingContext code in the view file looking like this:

<ContentPage.BindingContext>
    <viewmodel:MainViewModel x:Name="vm"/>
</ContentPage.BindingContext>

The name of the content page is MainPage.cs. Now in the MainPage.cs content page there is a control called grpList. So in the MainViewModel.cs file I try entering

Groups row = (Groups)grpList.SelectedRow;

and grpList isn't even found when I'm writing in the view model. However, if I write this in the content page's code-behind file, it is found and I have no problem.

So how can I access the page's controls and their properties from that pages view model?


Solution

  • You bind the properties of your view model to your controls. A view model is not meant to have knowledge of the view and its controls.

    So if you want the SelectedRow, you create a property in your view model and you bind to that property from your view.