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

MAUI中点击In按钮后Entry无法显示点击时间的问题

问题解决:Entry控件不显示In按钮点击时间&Android平台异常

核心问题拆解

  • UI无刷新机制:time1是普通属性,更新后没法通知界面同步,导致Entry控件不更新显示
  • 绑定语法错误:XAML里Source={Binding time1}属于冗余写法,且Path=Time完全错误——DateTime类型根本没有Time属性
  • 构造函数异步调用违规:构造函数不能用await,这会导致初始化流程异常,Android平台大概率因此出现绑定失效问题
  • 异步方法未等待:GetCachedLocation()是异步方法,调用时没加await,会导致位置获取逻辑异常(虽然不直接影响时间显示,但属于潜在bug)

修复步骤&代码

1. 给属性加通知机制

让页面类实现INotifyPropertyChanged接口,这样属性更新时能自动触发UI刷新

2. 修正XAML绑定写法

移除冗余的Source设置,直接绑定time1,并调整格式化字符串为正确的日期时间格式

3. 把异步位置获取移到合法生命周期方法

构造函数不能用await,把位置获取逻辑放到OnAppearing里执行

4. 异步方法调用加await

确保GetCachedLocation()执行完成,避免异步操作异常


修改后的后台代码

using System.ComponentModel;
using System.Runtime.CompilerServices;

public partial class DesktopStartupPage : ContentPage, INotifyPropertyChanged
{
    private DateTime _time1;
    public DateTime time1
    {
        get => _time1;
        set
        {
            if (_time1 != value)
            {
                _time1 = value;
                OnPropertyChanged();
            }
        }
    }

    public Location location { get; set; }

    public DesktopStartupPage()
    {
        InitializeComponent();
        time1 = DateTime.Now;
        BindingContext = this;
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        // 异步获取位置移到这里,避免构造函数用await
        location = await Geolocation.Default.GetLastKnownLocationAsync();
    }

    private void OnBackClicked(object sender, EventArgs e)
    {
        Shell.Current.GoToAsync("//MainPage");
    }

    private async void OnInClicked(object sender, EventArgs e)
    {
        time1 = DateTime.Now;
        Console.WriteLine(time1);
        // 加await等待异步方法完成
        var locationInfo = await GetCachedLocation();
        Console.WriteLine(locationInfo);
    }

    public async Task<string> GetCachedLocation()
    {
        try
        {
            if (location != null)
                return $"纬度: {location.Latitude}, 经度: {location.Longitude}, 海拔: {location.Altitude}";
        }
        catch (FeatureNotSupportedException fnsEx)
        {
            Console.WriteLine("位置功能不支持:" + fnsEx.Message);
        }
        catch (FeatureNotEnabledException fneEx)
        {
            Console.WriteLine("位置功能未启用:" + fneEx.Message);
        }
        catch (PermissionException pEx)
        {
            Console.WriteLine("位置权限未授权:" + pEx.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("获取位置出错:" + ex.Message);
        }
        return "无位置信息";
    }

    // INotifyPropertyChanged接口实现
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

修改后的XAML代码

<Button HeightRequest="60" WidthRequest="300" Grid.Row="3" x:Name="inbtn" Text="In" 
        Style="{StaticResource inButtonStyle}" SemanticProperties.Hint="点击记录时间" 
        Clicked="OnInClicked" HorizontalOptions="Center" />

<Button HeightRequest="60" WidthRequest="300" Grid.Row="3" x:Name="outbtn" Text="Out" 
        Style="{StaticResource outButtonStyle}" SemanticProperties.Hint="点击记录时间" 
        Clicked="OnOutClicked" HorizontalOptions="Center" />

<Entry Placeholder="点击In显示时间" Text="{Binding time1, StringFormat='点击时间:{0:yyyy-MM-dd HH:mm:ss}'}" 
       Style="{StaticResource tableContStyle}" Grid.Row="1" Grid.Column="0" />
<Entry Placeholder="点击Out显示时间" Text="{Binding time2, StringFormat='点击时间:{0:yyyy-MM-dd HH:mm:ss}'}" 
       Style="{StaticResource tableContStyle}" Grid.Row="1" Grid.Column="1" />

Android平台额外配置

要让位置功能正常运行,必须在AndroidManifest.xml中添加权限:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Android 10及以上版本,如果需要后台位置权限,还要额外添加对应权限,并在运行时主动请求用户授权。

内容的提问来源于stack exchange,提问作者Danul Hivi Vihan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:21:02