【问题标题】:Xamarin Forms can't find how to bind object with a detail viewXamarin Forms 找不到如何将对象与详细信息视图绑定
【发布时间】:2016-08-03 09:50:20
【问题描述】:

我正在使用 Xamarin 表单,在我的列表视图中单击元素后,我不想显示它的详细信息。它将打开一个包含详细信息的新视图。我不知道如何将整个对象绑定到视图,以便轻松使用他的属性。

这是我的代码:

   public partial class ContactDetailPage : ContentPage
        {
            public ContactDetailPage(Agency agencyItem)
            {
                InitializeComponent();
                // The agencyItem is get from a list view
                // HERE I suppose I need to bind the agencyItem to the view ?
            }
        }

这是我展示代理的详细视图:

<?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="Project.ContactDetailPage">
    <ContentPage.Content>
            <StackLayout Spacing="0">
                <Label Text="{Binding agency.name}" FontSize="Micro" LineBreakMode="TailTruncation" />
                <Label Text="{Binding agency.address}" FontSize="Micro" LineBreakMode="TailTruncation" />
            </StackLayout>

    </ContentPage.Content>
</ContentPage>

如何将视图绑定到 AgencyItem 以显示它?

【问题讨论】:

    标签: c# xaml listview xamarin xamarin.forms


    【解决方案1】:

    在此查看Xamarin documentation

    简短的回答是:

    BindingContext = agencyItem;

    BindingContext 是每个 Page 上的一个属性,它负责绑定等。请注意,如果名称直接在 agencyItem 中,则无需执行 &lt;Label Text="{Binding agency.name}" ... /&gt;。您可以直接使用&lt;Label Text="{Binding name}" ... /&gt;。所以从根对象开始。如果您的agencyItem 具有String 属性Name,则直接使用Name。如果agencyItem 有一个复杂的属性Agency 有一个String 属性Name,那么你当前的绑定是正确的。

    您也可以选择在 XAML 中执行此操作。然后你必须创建一个属性并实现 INotifyPropertyChanged 接口。

    我还注意到您没有使用像 MVVM 这样的模式。这可能也值得研究!

    【讨论】:

    • 在 MVVM 模式下看起来如何,这是一个非常简单的案例?
    • 真的!如果没有用例,请不要这样做!我只是想知道你是否知道它是否存在;)即使在一个小项目中它也可以带来好处。当然,我相信您的项目会很快变得非常庞大!
    【解决方案2】:

    您需要创建一个ListView,然后在其SelectedItem Property(如果您使用MVVM)或ItemSelected 事件或ItemTapped 事件中推送您的详细信息页面(即:navigate 到详细信息页面)。

    你可以在这里找到样品:

    1. ListView Sample 1
    2. ListView Further details
    3. 示例项目 - XamarinForms_Dynamic_ListView_Item
    4. Data Binding
    5. Lists in Xamarin.Forms

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      相关资源
      最近更新 更多