Forum Xamarin.Forms

Unknown member when subclassing ContentView

I'm subclassing a view off of a ContentView. However, at some point after this view is created, I want to interact with the ViewModel for this view. However, the function I'm calling the view from doesn't seem to know about that viewmodel - just that it's subclassed off of ContentView: I'm getting unknown member whenever I try to do something with myview.myviewmodel. What am I doing wrong?
Here's the code:

public partial class CardView : ContentView
public ViewModels.DetailViewModel detailvm;

public CardView()
    detailvm= new ViewModels.DetailViewModel();
    BindingContext = detailvm;


Then, where I'm calling it from, it gets initialized when some object gets initialized:

var card = new Views.CardView();

And then I try to call the VM in a different method inside this same object:

        Views.CardView card = cards[i];
        card.detailvm.MyProperty = something;

When I debug and mouse over that second line, I'm told:
"Unknown member: detailvm"

The weird thing is, I use this type of structure all the time with my pages. I create a new XAML page (it gets subclassed off of ContentPage or whatnot) and I stick a public viewmodel in it. Later on I access that viewmodel elsewhere, no problem. Are pages and views different in some fundamental way that doesn't let me do what I want? Do I need to create a special subclass of ContentView that allows me to access other objects I stick into my own subsequent subclasses? Any help would be appreciated!

P.S. I've now edited the XAML of the CardView and named one of the components as such:
<StackLayout x:Name="MyStack" etc.

I cannot access this stacklayout from outside, either.


  • SmeSme USMember ✭✭✭
    edited March 2017

    Usually with my pages, I set the binding context in the actual page. Then if I want to access the viewmodel through the objects in the page (ie, a ContentView) I would do it like so (ie, MyPage.xaml.cs):

    private ContentView myContentView;
    public MyPage()
        this.BindingContext = new MyViewModel();
        myContentView = new ContentView();
        this.Content = myContentView;
    var myViewModel = (MyViewModel)myContentView.BindingContext;
    myViewModel.MyProperty = ...
Sign In or Register to comment.