How to use compiled bindings with BindingContext in Xamarin XAML

457 views Asked by At

I want to use x:DataType with BindingContext like below.

<ContentPage
    x:DataType="local:MainPageViewModel">
    <ContentPage.BindingContext>
        <local:MainPageViewModel />
    </ContentPage.BindingContext>

    <Label
        x:DataType="local:TitleViewModel"
        BindingContext ="{Binding InnerViewModel}" 
        Text="{Binding Title}" />

</ContentPage>

Sorry @Jason, my previous mock code was too simplified to cause misleading.. Therefore I updated my mock code like below.

public class MainPageViewModel
{
    private TitleViewModel _innerViewModel;
    public TitleViewModel InnerViewModel
    {
        get => _innerViewModel;
        set => SetProperty(ref _innerViewModel, value);
    }
}

public class TitleViewModel
{
    private string _title;
    public string Title
    {
        get => _title;
        set => SetProperty(ref _title, value);
    }
}

The reason why I am not using InnerViewModel.Title for binding is PropertyChanged event only checks property path. So, If I update InnerViewModel.Title, it raise PropertyChanged event with path "Title", not "InnerViewModel.Title". It cause a problem.

I know I can do like below to solve,

public class MainPageViewModel
{
    private void OnInnerViewModelPropertyChanged(object sender, PropertyChangedArgs e)
    {
        // ...
        RaisePropertyChanged(this, "InnerViewModel.Title");
    }
}

But, I prefer to change BindingContext instead relaying PropertyChanged event.


However, it builds fail because of below reason.

Error XFC0045: Binding: Property "InnerViewModel" not found on "Local.TitleViewModel".

Even if I delete x:DataType like below, still fail because MainPageViewModel does not have Title property.

<Label
    BindingContext ="{Binding InnerViewModel}"
    Text="{Binding Title}" />

Therefore, I give up to compiled bindings by using x:null like below.

<Label
    x:DataType="x:null"
    BindingContext ="{Binding InnerViewModel}" 
    Text="{Binding Title}" />
0

There are 0 answers