Xamarin Forms MVVM 数据绑定在绑定到单个对象时失败



当我通过按钮从 ListView 单击时,我在详细信息页面上遇到数据无法正确绑定的问题。列表视图完美绑定,对象将传递到详细信息页面。读取对象的 Id,并从 API 调用对象的完整版本,并将其设置为对象的新实例。添加断点时,完整对象可用,但不会填充视图上的标签。下面是视图模型:

详细信息视图模型.cs

public class DetailsViewModel
{
public Deal Deal { get; set; }
public int DealId { get; set; }
public DetailsViewModel(int id)
{
Deal = new Deal();
DealId = id;
}
public async void GetDeal()
{
var deal = await Deal.GetDeal(DealId);
if(deal != null)
{
Deal = deal;
}
}
}

代码隐藏如下所示:

详细信息页面.Xaml.cs

DetailsViewModel viewModel;
int dealId;
public DetailPage(int id)
{
InitializeComponent();
dealId = id;
viewModel = new DetailsViewModel(dealId);
BindingContext = viewModel;
}
protected override void OnAppearing()
{
base.OnAppearing();
viewModel.GetDeal();
}

Xaml 文件是

详细信息页面.Xaml

<ContentPage.Content>
<ScrollView>
<StackLayout x:Name="detailsLayout">
<Label Text="{Binding Deal.Name}" />
</StackLayout>
</ScrollView>
</ContentPage.Content>

当我在 DetailsViewModel 上的 Deal = deal 中放置断点时,Deal 对象存在并且具有正确的数据,但我只是得到一个空白屏幕。我尝试过带有文本="{绑定名称}"和文本="{绑定 Deal.Name}"的标签。

我还尝试在ViewModel的GetDeal函数中手动创建交易,但仍然没有任何限制。

1( 确保您的属性通知 UI 实现 INotifyPropertyChanged 接口的更改。请参阅 https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm

2( 确保使用 Device.BeginInvokeOnMainThread 在 UI 线程上完成设置。https://learn.microsoft.com/fr-fr/dotnet/api/xamarin.forms.device.begininvokeonmainthread?view=xamarin-forms

using System.ComponentModel;
using System.Runtime.CompilerServices;
using Xamarin.Forms;
namespace YourNamespace
{
public class DetailsViewModel : INotifyPropertyChanged
{
private Deal _deal;
public Deal Deal
{
get => _deal;
set
{
if (_deal != value)
{
_deal = value;
OnPropertyChanged();
}
}
}
public int DealId { get; set; }
public DetailsViewModel(int id)
{
//!! useless assignation
//Deal = new Deal();
DealId = id;
}

public async void GetDeal()
{
var deal = await Deal.GetDeal(DealId);
if (deal != null)
{
//Ensure we are on UI thread
Device.BeginInvokeOnMainThread(() => Deal = deal);
}
}

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

相关内容

  • 没有找到相关文章

最新更新