【问题标题】:Use custom DataTemplate in XF with XAML在 XF 中通过 XAML 使用自定义 DataTemplate
【发布时间】:2016-04-21 05:54:16
【问题描述】:

此代码正在运行:

<ListView ItemsSource="{Binding ItemsSourcePrimary}" VerticalOptions="FillAndExpand">
    <ListView.ItemTemplate>
      <DataTemplate>

        <ViewCell>
          <ViewCell.View>
            <StackLayout Padding="15, 5, 15, 5" Orientation="Horizontal" HorizontalOptions="FillAndExpand">
              <Image Source="{Binding IconSource}" Aspect="AspectFit" HorizontalOptions="Center" VerticalOptions="Center" />
              <Label Text="{Binding Title}" VerticalOptions="Center" />
            </StackLayout>
          </ViewCell.View>
        </ViewCell>

      </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

但我想像这样将一个部分分成一个类:

<ListView ItemsSource="{Binding ItemsSourcePrimary}" VerticalOptions="FillAndExpand">
    <ListView.ItemTemplate>
      <DataTemplate>

        <local:MenuListCell Title="{Binding Title}" IconSource="{Binding IconSource}" />

      </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

但我有一个错误:

找不到文本名称的属性

我使用以下代码在 xaml 文件中实现类 MenuListCell:

<?xml version="1.0" encoding="utf-8" ?>
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Test.MenuListCell">

    <ViewCell.View>
        <StackLayout Padding="15, 5, 15, 5" Orientation="Horizontal" HorizontalOptions="FillAndExpand">
          <Image Source="{Binding IconSource}" Aspect="AspectFit" HorizontalOptions="Center" VerticalOptions="Center" />
          <Label Text="{Binding Title}" VerticalOptions="Center" />
        </StackLayout>
    </ViewCell.View>

</ViewCell>

你有解决办法吗? 我们是否需要创建一个 c# 文件 .cs 来实现这些属性,或者我们可以在 xaml 中完成它?

【问题讨论】:

    标签: c# xamarin xamarin.forms


    【解决方案1】:

    如果您始终将MenuListCell 绑定到相同类型的对象,则只需更改

    <local:MenuListCell Title="{Binding Title}" IconSource="{Binding IconSource}" />
    

    <local:MenuListCell />
    

    单元格的 Datacontext 是您的项目。所以Title in

     <Label Text="{Binding Title}" VerticalOptions="Center" />
    

    是列表项的属性。

    【讨论】:

    • 好的,但是使用这个方法,我得到这个错误:“System.NullReferenceException:对象引用未设置为对象的实例”你有什么想法吗?直接与 ViewCell 相同的代码正在工作
    • 没有堆栈跟踪,这并不容易。如果数据正确,它应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    相关资源
    最近更新 更多