0
我正在創建一個ListView,其中的項目我想用代碼直接控制。我有以下xaml聲明一個通用的ListView。Xamarin Forms - 在ViewCell中訪問數據綁定對象
<?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構造函數中爲null。
謝謝,我實際上已經嘗試過,但它在構造函數中爲空(問題已更新以反映此問題)。是否有另一個BindingContext不爲null的事件,但它是創建控件的好地方? –
有一個BindingContextChanged事件可以使用 – Jason
看來OnAppearing是一個好方法。我可以在那裏訪問BindingContext。 –