You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI中TimePicker值无法与ViewModel绑定问题求助

解决MAUI TimePicker与CommunityToolkit.Mvvm双向绑定失效问题

你的问题核心是类型不匹配:MAUI的TimePicker.Time属性对应的是TimeSpan类型,但你的ViewModel里声明的是DateTime类型,导致绑定无法正常工作——默认显示12:00 AM(对应DateTime.MinValue的时间部分),且选中值无法同步到ViewModel。

解决方案步骤

1. 修改ViewModel的属性类型

将ViewModel中的DateTime类型改为TimeSpan,还可以设置合理的默认值避免初始显示12:00 AM:

namespace CRUDappMAUI.ViewModel
{
    public partial class AddLeaveViewModel : ObservableObject
    {   
        [ObservableProperty]
        TimeSpan _time1 = TimeSpan.FromHours(9); // 默认显示9:00 AM

        [ObservableProperty]
        TimeSpan _time2 = TimeSpan.FromHours(17); // 默认显示5:00 PM

        [RelayCommand]
        public async void SubmitClicked()
        {
            try
            {                
                Debug.WriteLine(Time1);
                Debug.WriteLine(Time2);               
            }
            catch (Exception ex) {              
                Debug.WriteLine(ex.ToString());            
            }
        }
    }
}

2. 确认BindingContext已正确设置

确保页面的BindingContext指向ViewModel实例,否则绑定完全不会生效:

  • 方式一(XAML中设置):
<ContentPage.BindingContext>
    <vm:AddLeaveViewModel xmlns:vm="clr-namespace:CRUDappMAUI.ViewModel" />
</ContentPage.BindingContext>
  • 方式二(后台代码中设置):
public AddLeavePage()
{
    InitializeComponent();
    BindingContext = new AddLeaveViewModel();
}

3. 保留原XAML绑定代码

你的XAML绑定代码无需修改,类型匹配后双向绑定会自动生效:

<TimePicker 
    Time="{Binding Time1, Mode=TwoWay}"
    FontSize="Medium"
    Grid.Column="0"
    Grid.Row="1"
    x:Name="time1"
    IsEnabled="{Binding Time1IsEnabled, Mode=TwoWay}"/>

<TimePicker
    Time="{Binding Time2, Mode=TwoWay}"
    FontSize="Medium"
    Grid.Column="1"
    Grid.Row="1"
    x:Name="time2"
    IsEnabled="{Binding Time2IsEnabled, Mode=TwoWay}"/>

内容的提问来源于stack exchange,提问作者Lasitha Lankajeewa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 09:31:42