Passing in a DateTime as Command Parameter

mrizoiwe98 66 Reputation points
2021-03-31T03:09:36.727+00:00

Hello , how can I pass a DateTime type into a Command Parameter? In this case I want to try pass Datetime.Now

My Xaml:

<Button Text="Click me" Command="{Binding MyCommand}" VerticalOptions="EndAndExpand" Margin="0,0,0,25"></Button>

My Viewmodule:

public class MainViewModule : INotifyPropertyChanged
    {

        public ICommand MyCommand{ get; }

        public MainViewModule()
        {
            MyCommand= new Command<DateTime>(Foo);
       )
 }


        void Foo(DateTime dateTime)
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                await App.Current.MainPage.DisplayAlert("", $"you passed {dateTime}", "OK");
            });
        }
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,292 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JessieZhang-MSFT 7,706 Reputation points Microsoft Vendor
    2021-03-31T05:50:32.11+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    You could do this by referencing the System namespace in Xaml. This can be done in the first Xaml element's attributes, e.g.:

    <ContentPage   
         ....  
         xmlns:sys="clr-namespace:System;assembly=mscorlib" >  
    

    Then you can pass in the DateTime.Now as a CommandParameter for the button, e.g.:

        <Button Text="Click me" Command="{Binding MyCommand}" CommandParameter="{Binding Source={x:Static sys:DateTime.Now}}" VerticalOptions="EndAndExpand" Margin="0,0,0,25"></Button>  
    

    Then the following Command code should receive the parameter:

            MyCommand = new Command<DateTime>(fooObject =>  
            {              
                //add your code here, fooObject should have your DateTime.Now  
                 
            });  
    

    However, since DateTime.Now is globally available, there is no need to do this as you can just get the current DateTime.Now when the command runs.

    Best Regards,

    Jessie Zhang

    ---
    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments