1
我想要獲得自定義視圖的自定義列表(我最終將添加控件到每個視圖)使用數據綁定顯示在一個xamarin項目。但是當我運行我的項目時,沒有任何東西出現在列表中。我對數據綁定的東西很陌生,所以我有點困惑。我搜索並嘗試了一些其他解決方案,但一直未能找出我的具體問題。任何幫助,將不勝感激。這是我的代碼:ListView與自定義視圖的數據綁定
<?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="XamarinTuts.XMainPage">
<ContentPage.Content>
<StackLayout>
<Label Text="Tasks:" HorizontalTextAlignment="Start" VerticalTextAlignment="Start" x:Name="tasksLabel"></Label>
<ListView ItemsSource="{Binding taskItems}">
<ListView.ItemTemplate>
<DataTemplate>
<Frame BackgroundColor="Black" Padding="5">
<Grid>
<StackLayout Name="TextStack" Orientation="Vertical" Grid.Column="0">
<Label Text="{Binding Name}"></Label>
<Label Text="{Binding Description}"></Label>
</StackLayout>
<StackLayout Name="ButtonStack" Orientation="Horizontal" HorizontalOptions="End" Grid.Column="1">
<Button Name="Edit" Text="Edit" Width="50" Height="50"></Button>
</StackLayout>
</Grid>
</Frame>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
這是我的XAML。這裏是我的XMainPage.cs:
public partial class XMainPage : ContentPage
{
TestViewModel vm;
public XMainPage()
{
InitializeComponent();
vm = new TestViewModel();
TaskListItem testItem = new TaskListItem(this, "Go shopping", "Drive to meijer and get the following: Milk, Eggs, Booze");
TaskListItem testItem2 = new TaskListItem(this, "Play Overwatch", "Pwn some n00bs");
vm.taskItems.Add(testItem);
vm.taskItems.Add(testItem2);
BindingContext = vm;
}
}
由我TestViewModel.cs如下:
public class TestViewModel : INotifyPropertyChanged
{
ObservableCollection<TaskListItem> mtaskItems;
public TestViewModel()
{
mtaskItems = new ObservableCollection<TaskListItem>();
}
public ObservableCollection<TaskListItem> taskItems
{
get
{
return mtaskItems;
}
set
{
mtaskItems = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string name = null)
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(name));
}
}
由我TaskListItem.cs如下:
public class TaskListItem : ViewCell
{
public Task newTask;
String mName;
String mDescription;
public String Name
{
get
{
return mName;
}
}
public String Description
{
get
{
return mDescription;
}
}
public TaskListItem(ContentPage taskListItemParent, String TaskName, String TaskDescription)
{
//newTask = new Task(TaskName, TaskDescription);
mName = TaskName;
mDescription = TaskDescription;
}
}
我已更新我的代碼與您的建議,它仍然不適合我。它看起來像我已經正確設置,但沒有顯示在網頁上。我還錯過了什麼嗎? – Jremery1337
原來我有一些無效的XAML。擺弄一下後,我能夠正確顯示它。謝謝你的幫助! – Jremery1337
它很糟糕,在編譯時無法找到這些錯誤。我很高興這些信息是有幫助的 –