【问题标题】:Xamarin Forms - access databound object in ViewCellXamarin Forms - 访问 ViewCell 中的数据绑定对象
【发布时间】:2017-01-16 20:57:43
【问题描述】:

我正在创建一个 ListView,我想用代码直接控制其项目。我有以下声明通用 ListView 的 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"
             xmlns:local="clr-namespace:ViewCellClick"
             x:Class="ViewCellClick.MainPage">
    <ListView x:Name="___listview" HasUnevenRows="True">
        <ListView.ItemTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

然后在后面的代码中,我设置了 ItemsSource 属性。

namespace ViewCellClick
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            ___listview.ItemsSource = Repository.GetList();
            ___listview.ItemTemplate = new DataTemplate(typeof(CustomViewCell));
        }
    }

这利用了自定义模板定义为...

    public class CustomViewCell : ViewCell
    {
        public CustomViewCell()
        {
            var stack = new StackLayout();

            stack.Children.Add(new Label() { Text = "Label" });

            // HOW DO I ACCESS THE MODEL HERE SO I CAN DRAW CUSTOM UI DEPENDING ON THE MODEL INSTANCE?

            View = stack;
        }
    }
}

在这个级别,我有一个非常通用的自定义视图单元格,因为它只创建一个标签。但是,假设模型很复杂,并且根据模型中的数据,我会为该 ViewCell 实例绘制不同的 UI。

如何访问每个 CustomViewCell 的模型,然后根据该模型绘制 UI?

我尝试了 BindingContext,但它在 CustomViewCell 构造函数中为空。

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    ViewCell 的BindingContext 将引用列表中的当前项。您需要将其转换为适当的类型才能使用它。

    【讨论】:

    • 谢谢,我实际上已经尝试过了,但它在构造函数中为空(已更新问题以反映这一点)。是否还有另一个 BindingContext 不为 null 的事件,但它是创建控件的好地方?
    • 您可以使用 BindingContextChanged 事件
    • 看来 OnAppearing 是个好办法。我可以访问那里的 BindingContext。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多