![](/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.