如何将 Maui .NET DatePicker 的日期默认为今天的日期?

问题描述 投票:0回答:1
每当我加载“事件”页面时,它总是将日期默认为 1924 年的某个随机日期。如何将日期默认为今天的日期,以便用户不必滚动浏览当时和现在之间的所有日期来选择未来的日期?

    我尝试在InitializeComponent之后设置EventDate
  • 我尝试在 XAML 中设置默认日期,但发现设置默认日期后无法更新绑定
  • 我尝试通过自动将其分配给属性本身来默认它
.net datepicker maui
1个回答
0
投票
您可以通过更新 ContentPage 构造函数中的绑定属性来设置任何控件的默认值。

更新Property时,需要确保在类构造函数中调用InitializeComponent()之前更新它,否则一旦表单加载,该值将重置为默认值。

例如活动内容页.cs

public partial class EventPage : ContentPage { public EventPage() // All pages need a default, empty constructor for the XAML previewer { EventDate = DateTime.Now; // Any default page values must be set before InitializeComponent() is called, otherwise the values get overridden InitializeComponent(); BindingContext = this; } public DateTime EventDate { get; set; } // The properties that the page binds to need to have the same name as the properties in the model }
和事件ContentPage.xaml

<VerticalStackLayout> <DatePicker Grid.Column="1" Date="{Binding EventDate}" Format="D"/> </VerticalStackLayout>
    
© www.soinside.com 2019 - 2024. All rights reserved.