![](/img/trans.png)
[英]Set BindingContext to ViewModel in XAML on Xamarin.Forms
[英]xamarin BindingContext with ViewModel
我有數據綁定問題我有一個標簽頁包含兩個標簽聊天和組。
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="bashal.MainPage" Title="Bashal"
xmlns:local="clr-namespace:bashal.Views"
xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
android:TabbedPage.ToolbarPlacement="Bottom" >
<local:chatPage Title="chats" />
<local:groupsPage Title="Groups" NavigationPage.HasBackButton="False" />
</TabbedPage>
第一個名為聊天的選項卡包含此頁面。
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" x:Class="bashal.Views.chatPage"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:ViewModels="clr-namespace:bashal.ViewModels"
Title="home" >
<ContentPage.BindingContext>
<ViewModels:chatPageViewModel/>
</ContentPage.BindingContext>
<StackLayout>
<CollectionView
>
<CollectionView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding name}"/>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
</ContentPage>
我正在嘗試使用名為 vaiewModels 的文件夾中的 ViewModel class 進行數據綁定
namespace bashal.ViewModels
{
class chatPageViewModel
{ ObservableCollection<rooms> rooms;
public chatPageViewModel()
{
rooms = new ObservableCollection<rooms>
{
new rooms {name = "user1", discrbtion= "welcome"},
new rooms {name = "user2", discrbtion= "welcome"},
new rooms {name = "user3", discrbtion= "welcome"},
new rooms {name = "user4", discrbtion= "welcome"},
new rooms {name = "user5", discrbtion= "welcome"},
new rooms {name = "user6", discrbtion= "welcome"}
};
}
}
}
這個房間 class
public class rooms
{
public string name { get; set; }
public string discrbtion { get; set; }
}
但數據沒有顯示我做錯了什么? 提前致謝
首先,您需要分配一個ItemsSource
<CollectionView ItemSource="{Binding rooms}" >
你只能綁定到公共屬性,所以rooms
需要是公共屬性
public ObservableCollection<rooms> rooms { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.