Anthony Kallay
Anthony Kallay

Reputation: 133

ContentView as Control with own ViewModel

Been struggling with this for a while, i have a control inherited from ContentView that has its own ViewModel to manage a variery of paremeters, from the parent page i need to pass just one Property, however i just cant get it to pass across into the ViewModel, if i sont use a view model i use the below and it works fine

Parent Page

 <controls:CountdownTimerControl EndDate="{ Binding BidEndDate}">

Control

public static readonly BindableProperty EndDateProperty =
    BindableProperty.Create(nameof(EndDate), typeof(DateTime), typeof(CountdownTimerControl), default(DateTime), BindingMode.TwoWay,
       propertyChanged: (bindable, oldVal, newVal) => ((CountdownTimerControl)bindable).OnIsShown((DateTime)newVal));

    public DateTime EndDate
    {
        get => (DateTime)GetValue(EndDateProperty);
        set => SetValue(EndDateProperty, value);
    }

However if i change my control to use a view model, then the above p[roperty isnt passed via the BindableProperty

<controls:CountdownTimerControl EndDate="{ Binding BidEndDate}">
                                                <controls:CountdownTimerControl.BindingContext>
                                                    <viewModels:CountdownViewModel></viewModels:CountdownViewModel>
                                                </controls:CountdownTimerControl.BindingContext>
                                            </controls:CountdownTimerControl>

Then it doesnt pass the property at all

Struggling and would appreciate any help

Cheers A

Upvotes: 1

Views: 1573

Answers (1)

user10398433
user10398433

Reputation: 426

Instead of EndDate = "{Binding BidEndDate}",

write EndDate="{Binding Source={x:Reference dem}, Path=BindingContext.BidEndDate}"

Where 'dem' is the name of the main page.

 <?xml version="1.0" encoding="utf-8" ?>
 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:Markup="clr-namespace:Demo.Helper.MarkupExtensions"
         xmlns:viewModels="clr-namespace:Demo.ViewModels"
         xmlns:controls="clr-namespace:Demo.Views.UserControls"
         x:Name="dem"
         x:Class="Demo.Views.Dem">

<ContentPage.BindingContext>
    <viewModels:DemVM />
</ContentPage.BindingContext>

    <controls:CountdownTimerControl EndDate="{Binding Source={x:Reference dem}, Path=BindingContext.BidEndDate}">
        <controls:CountdownTimerControl.BindingContext>
            <viewModels:CountdownViewModel/>
        </controls:CountdownTimerControl.BindingContext>
    </controls:CountdownTimerControl>

</ContentPage>

Upvotes: 1

Related Questions