我试图在点击事件时打开一个新的 Page
,它应该显示某个对象的一些详细信息。为此,我需要将对象本身或其 ID 传递给新页面。所以我在详情页的构造函数中添加了一个参数,如下所示。
void onItemTapped(object sender, ItemTappedEventArgs e)
{
if (e.Item != null)
{
bool convOk = Int32.TryParse((string)e.Item, out int id);
if (convOk)
{
Navigation.PushAsync(new DetailPage(id));
}
}
}
并且 DetailPage
有自己的 DetailViewModel
,它在代码隐藏中被设置为 BindingContext
。
DetailPage
XAML:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Foo.Views.DetailPage">
<ContentPage.Content>
<StackLayout Orientation="Vertical">
<Label Text="FooBar" />
<Label Text="{Binding trackID}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
DetailPage
代码隐藏
namespace Foo.Views
{
public partial class DetailPage : ContentPage
{
public DetailPage(int trackID)
{
InitializeComponent();
BindingContext = new DetailViewModel(trackID);
}
}
}
DetailViewModel
:
namespace Foo.ViewModels
{
public class DetailViewModel : BaseViewModel
{
// trackID prop
int _trackID;
int trackID
{
get { return _trackID; }
set
{
_trackID = value;
notifyPropertyChanged(nameof(trackID));
}
}
public TargetDetailViewModel(int tid)
{
trackID = tid;
}
}
}
但是,DetailPage
和DetailViewModel
之间的绑定(bind)似乎不起作用,页面不显示任何内容。 ID 本身一直正确传递到 DetailViewModel
。
这是因为初始化的顺序吗?我假设用 XAML 编写的所有内容都将在 DetailPage.InitializeComponent()
方法中执行?如果那是正确的,那么在 DetailPage.InitializeComponent()
之前实例化 ViewModel
是否安全/正确?
任何提示表示赞赏。
最佳答案
您的 trackID
属性未公开。
注意:如果您查看应用程序日志输出,您可以发现这样的绑定(bind)问题(通过字符串 Binding:
过滤)
未绑定(bind)私有(private)变量的日志示例:
Binding: 'trackID' property not found on 'XXXX.VM', target property: 'Xamarin.Forms.Label.Text'
DetailViewModel 修复:
public class DetailViewModel : BaseViewModel
{
int _trackID;
public int trackID;
{
get { return _trackID; }
set
{
_trackID = value;
notifyPropertyChanged(nameof(trackID));
}
}
~~~~
}
关于c# - Xamarin 在页面之间传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54517847/