由于与 Shell 一起使用时最新的 CommunityToolkit.Maui.Mvvm 包存在错误,我没有使用它。所以我只是在代码中编写所有内容(没有 Xaml)。据我所知,这应该可行。我希望最后更新标签的文本会更新,但事实并非如此。谁能看到为什么不呢?
namespace MyMauiApp;
public class DashboardPage : ContentPage
{
private string _lastUpdated;
private bool _loading;
public DashboardPage()
{
LoadData = new AsyncCommand(SetData);
RefreshView refreshView = new();
refreshView.RefreshColor = ColourConstants.DesaturatedDark;
refreshView.Bind(RefreshView.IsRefreshingProperty, nameof(_loading));
refreshView.Bind(RefreshView.CommandProperty, nameof(LoadData));
ScrollView scrollView = new();
var dashgrid = new Grid
{
RowDefinitions =
{
new RowDefinition { Height = new GridLength(0, GridUnitType.Auto) },
},
ColumnDefinitions =
{
new ColumnDefinition { Width = new GridLength(0, GridUnitType.Auto) },
new ColumnDefinition { Width = new GridLength(0, GridUnitType.Auto) },
},
}.CenterVertical();
dashgrid.Add(new Label { Text = "Last Updated:" }, 0, 0);
Label lastUpdated = new() { HorizontalTextAlignment = TextAlignment.End };
lastUpdated.SetBinding(Label.TextProperty, nameof(LastUpdated));
dashgrid.Add(lastUpdated, 1, 0);
scrollView.Content = dashgrid;
refreshView.Content = scrollView;
Content = refreshView;
}
public string LastUpdated
{
get => _lastUpdated;
set
{
OnPropertyChanged(nameof(LastUpdated));
_lastUpdated = value;
}
}
public AsyncCommand LoadData { get; }
private async Task SetData()
{
try
{
LastUpdated = DateTime.Now.ToString("dd/MM/yy hh:mm tt");
}
catch (Exception)
{
Debug.WriteLine("Failed to set data");
}
finally
{
_loading = false;
}
}
protected override void OnAppearing()
{
base.OnAppearing();
_ = SetData();
}
}
您的代码有两个问题。首先,您没有设置BindingContext
任何控件,因此即使设置正确,绑定也不会起作用。你的定义Label
应该是这样的:
Label lastUpdated = new() { HorizontalTextAlignment = TextAlignment.End };
lastUpdated.BindingContext = this;
lastUpdated.SetBinding(Label.TextProperty, nameof(LastUpdated));
其次,属性的设置器LastUpdated
是错误的。首先,您设置支持字段值,然后调用OnPropertyChanged
以便代码知道发生了更改并且可以传播更新的值:
public string LastUpdated
{
get => _lastUpdated;
set
{
_lastUpdated = value;
OnPropertyChanged(nameof(LastUpdated));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句