【发布时间】:2017-09-12 02:00:34
【问题描述】:
我想在没有发生的条目上显示它,如果我使用带有消息中心的视图模型它不会显示,请告诉我我做错了什么我应该做什么。我认为该条目在消息中心中找不到值。
<?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="Data1.Views.Page1">
<ContentPage.Content>
<ListView x:Name = "lstView" ItemTapped="OnItemTapped" />
</ContentPage.Content>
</ContentPage>
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
lstView.ItemsSource = new List<string>() { "Vegetables", "Fruits", "Flower Buds", "Legumes", "Bulbs", "Tubers" };
}
void OnItemTapped(object sender, ItemTappedEventArgs e)
{
if (e == null) return; // has been set to null, do not 'process' tapped event
Debug.WriteLine(e.Item);
((ListView)sender).SelectedItem = null; // de-select the row
var person = new Person
{
Name = e.Item.ToString()
};
MessagingCenter.Send<Page1, string>(this, "Hi", e.Item.ToString());
Navigation.PushModalAsync(new Page2());
}
}
public partial class Page2 : ContentPage
{
public Page2()
{
InitializeComponent();
MessagingCenter.Subscribe<Page1, string>(this, "Hi", (sender, arg) =>
{
txttest.Text = arg;
});
}
}
【问题讨论】:
-
您在 Page2 创建之前发送消息,因此它还不存在接收消息。 MessagingCenter 不会将消息排队以供将来传递。在这种情况下,将值作为参数传递给 Page2 的构造函数会简单得多。
-
即使我使用它并将其绑定到条目仍然没有:public class MainViewModel { public Person Person { get;放; } public MainViewModel() { MessagingCenter.Subscribe
(this, "Hi", (sender, arg) => { Person = new Person { Name = arg }; }); } } -
没有在上下文中看到该代码,我无法判断它是否解决了我提到的问题。
标签: c# xamarin.forms