question

mrizoiwe98 avatar image
0 Votes"
mrizoiwe98 asked JessieZhang-2116 edited

Passing in a DateTime as Command Parameter

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");
             });
         }





dotnet-xamarinforms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JessieZhang-2116 avatar image
0 Votes"
JessieZhang-2116 answered JessieZhang-2116 edited

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.





5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.