Rafael
Rafael

Reputation: 2019

How to display Xamarin date picker upon clicking a button in viewmodel

In my platform agnostic Xamarin project, in the page view model (MVVM approach used) I have a command with the following code:

        DateSelectionCommand = new Command(() =>
        {
            DatePicker datePicker = new DatePicker();
            datePicker.IsEnabled = true;
            datePicker.IsVisible = true;
            datePicker.Focus();
        });

This approach advised on Xamarin forums and I expect that when I have clicked on the button connected to the DateSelectionCommand the datepicker should be displayed. But it does not.

I have set handler on Focused event for DatePicker, but it does not get noticed when I call datePicker.Focus().

Is there a straightforward way to display Xamarin datepicker when I click on a button?


UPDATE

I've been advised to add datepicker to the page layout (thanks @sushihangover).

In case I am calling this code in viewmodel, that does not know about the page layout, is it possible to solve this task?

Upvotes: 0

Views: 1718

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

You could pass the DatePicker as CommandParameter to ViewModel

in xaml

<StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">

        <Button  Text="OpenPicker" Command="{Binding DateSelectionCommand}" CommandParameter="{Binding Source={x:Reference picker} ,Path=.}" HeightRequest="40" WidthRequest="200" />

        <DatePicker x:Name ="picker"  IsVisible="false" />

</StackLayout>

in code behind

DateSelectionCommand = new Command((arg)=> {

       var picker = arg as DatePicker;

       picker.IsEnabled = true;
       picker.IsVisible = true;
       picker.Focus();
              
            
});

Upvotes: 2

Related Questions