I'm having trouble binding values to a custom ContentView I have.
I have a ContentPage that uses a AccountStatusView that is a ContentView and has a BindableProperty. This BindableProperty is of type AccountStatus. When I try to use binding, the BindableProperty is never udpated.
Does someone know why this doesn't work?
MainPage - xaml
<Grid>
<controls:AccountStatusView AccountStatus="{Binding AccountStatus}" />
</Grid>
MainPage - C#
public partial class MainPage : ContentPage
{
public MainPage(ViewModel vm) {
BindingContext = vm;
InitializeComponent();
}
}
ViewModel
public partial class ViewModel : ObservableObject
{
[ObservableProperty] private AccountStatusDto _accountStatus;
// . . .
public async Task InitializeAsync()
{
AccountStatus = await _repo.GetAccountStatus();
}
}
AccountStatusView
public partial class AccountStatusView : ContentView
{
public static readonly BindableProperty AccountStatusProperty =
BindableProperty.Create(nameof(AccountStatus), typeof(AccountStatusDto), typeof(AccountStatusView), propertyChanged: DoSomething);
public static void DoSomething(BindableObject bindable, object oldvalue, object newvalue)
{
// do something with the new value
}
public AccountStatusDto AccountStatus
{
get => (AccountStatusDto)GetValue(AccountStatusProperty);
set => SetValue(AccountStatusProperty, value);
}
}
EDIT
I found this answer by ToolmakerSteve,
When making a custom component (that includes XAML), DO NOT set BindingContext = this;
And
ACCESS COMPONENT PROPERTIES VIA x:Name
Solution: Give the custom component (card) an x:Name, and make that the "Source" of those bindings:
<VerticalStackLayout ... x:Name="me" <-- IMPORTANT! Change name as desired. x:Class="DataBindingExample.Card"> ... <Label Text="{Binding CardIncrement, Source={x:Reference me}}" ...
And it worked perfectly
falseis the default value that you can give to the property. It's optional since the method signature assignsdefaultto that parameterthis.Content.BindingContext = new MyViewModel();