Xaml 如何将值从viewmodel绑定到listview

Xaml 如何将值从viewmodel绑定到listview,xaml,xamarin.forms,data-binding,binding,Xaml,Xamarin.forms,Data Binding,Binding,我有一个ViewModel,它具有填充值的比例和方法: public class MRateReportViewModel : HeaderViewModel { public ICommand ChangeReportPeriodCommand { get; } public ICommand BackToHomePageCommand { get; } public string Hashtag { get; set; } public string Rat

我有一个ViewModel,它具有填充值的比例和方法:

public class MRateReportViewModel : HeaderViewModel
{
    public ICommand ChangeReportPeriodCommand { get; }
    public ICommand BackToHomePageCommand { get; }

    public string Hashtag { get; set; }
    public string Rating { get; set; }
    public decimal? mTP { get; set; }
    public string Image { get; set; }
    public string Date { get; set; }

    public DateTime MinimumDate { get; set; }
    public DateTime MaximumDate { get; set; }
    public DateTime PickedDate { get; set; }

    public ObservableCollection<UserEventModel> UserEventsCollection { get; set; }
    private UserEventsModel userEventsModel;
    private ObservableCollection<EventTypeAtributtes> EventTypes;
    public string EventType;

    public List<String> EvtList { get; set; }

    public MRateReportViewModel()
    {
        UserEventsCollection = new ObservableCollection<UserEventModel>();
        userEventsModel = new UserEventsModel();
        ChangeReportPeriodCommand = new Command((dailyOrTotal) => ChangeReportPeriod(dailyOrTotal.ToString()));

        BackToHomePageCommand = new Command(() => BackToHomePage());
        InitData();
    }

    private async void InitData()
    {
        ShowDialog();
        userEventsModel = await EventService.GetEvents();
        EventTypes = await EventService.GetEventType();

        foreach (var item in userEventsModel.Events)
        {
            UserEventsCollection.Add(item);
        }
        HideDialog();
        Page++;
    }
}
公共类MRateReportViewModel:HeadServiceWModel
{
公共ICommand ChangeReportPeriodCommand{get;}
公共ICommand BackToHomePageCommand{get;}
公共字符串哈希标记{get;set;}
公共字符串评级{get;set;}
公共十进制数?mTP{get;set;}
公共字符串图像{get;set;}
公共字符串日期{get;set;}
公共日期时间最小日期{get;set;}
公共日期时间最大日期{get;set;}
公共日期时间选取日期{get;set;}
公共ObservableCollection UserEvents集合{get;set;}
私有用户事件模型用户事件模型;
私有可观察收集事件类型;
公共字符串事件类型;
公共列表EvtList{get;set;}
公共MRaterPortViewModel()
{
UserEventsCollection=新的ObservableCollection();
userEventsModel=新的userEventsModel();
ChangeReportPeriodCommand=新命令((dailyOrTotal)=>ChangeReportPeriod(dailyOrTotal.ToString());
BackToHomePageCommand=新命令(()=>BackToHomePageCommand());
InitData();
}
私有异步void InitData()
{
ShowDialog();
userEventsModel=Wait EventService.GetEvents();
EventTypes=等待EventService.GetEventType();
foreach(userEventsModel.Events中的变量项)
{
UserEventsCollection.Add(项);
}
HideDialog();
Page++;
}
}
通过调试,我检查了EventDetails方法,并获得了正确的值。 在视图中,我有一个带有ListView的页面,我应该用viewmodel中的值填充该页面:

<ListView ItemsSource="{Binding EventsList}"
                      CachingStrategy="RecycleElement"
                      x:Name="EventsDiary"
                      ItemAppearing="EventsDiary_ItemAppearing"
                      SelectionMode="None"
                      HasUnevenRows="True"
                      Margin="0,0,0,10">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <material:MaterialCard HorizontalOptions="FillAndExpand"
                                                   VerticalOptions="FillAndExpand"
                                                   CornerRadius="2"
                                                   Margin="10,0,10,15"
                                                   HeightRequest="178"
                                                   Padding="0"
                                                   BackgroundColor="#f4f4f4">
                                <Grid RowSpacing="0">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="auto" />
                                        <ColumnDefinition Width="auto" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="auto" />
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="6" />
                                        <RowDefinition Height="auto" />
                                        <RowDefinition Height="auto" />
                                        <RowDefinition Height="auto" />
                                        <RowDefinition Height="auto" />
                                    </Grid.RowDefinitions>
                                    <BoxView Grid.Column="0"
                                             Grid.ColumnSpan="5"
                                             Grid.Row="0"
                                             BackgroundColor="{StaticResource CustomizedRedColor}"
                                             CornerRadius="4"
                                             Margin="0" />

                                    <RelativeLayout Grid.Column="0"
                                                    Grid.Row="1"
                                                    Margin="10,10,0,0">
                                        <controls:CircleImage HeightRequest="90"
                                                              WidthRequest="90"
                                                              Source="serpa1.png"
                                                              Aspect="AspectFill">
                                        </controls:CircleImage>

                                        <material:MaterialCard HeightRequest="30"
                                                               WidthRequest="30"
                                                               CornerRadius="50"
                                                               BackgroundColor="#525252"
                                                               Margin="0"
                                                               Padding="0"
                                                               Opacity="0.9">
                                            <Label Text="1"
                                                   TextColor="White"
                                                   HorizontalOptions="CenterAndExpand"
                                                   VerticalOptions="CenterAndExpand" />
                                        </material:MaterialCard>
                                    </RelativeLayout>

                                    <StackLayout Grid.Column="1"
                                                 Grid.ColumnSpan="3"
                                                 Grid.Row="1"
                                                 Padding="0"
                                                 Margin="0"
                                                 Orientation="Vertical"
                                                 Spacing="0">

                                        <Label Text="Ključne reči"
                                               FontSize="18"
                                               Margin="0,5,0,0"
                                               TextColor="#03414e"
                                               FontFamily="{StaticResource BalooBhai}" />

                                        <Label Text="{Binding Hashtag}"
                                               FontSize="12"
                                               Margin="0"
                                               VerticalOptions="StartAndExpand"
                                               TextColor="#030303" />

这是xaml代码的一部分。在这个例子中,我应该绑定Hashtag值,但它仍然是空的

以下是我为UserEventsModel提供的服务:

public static async Task<UserEventsModel> GetEvents()
        {
            UserEventsModel userEventModel = new UserEventsModel();
            try
            {
                //string url = UrlConstants.GET_USER_EVENTS;
                string url = UrlConstants.USER_DIARY;

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", LocalDataHelper.RestoreCookie());
                    string content = Newtonsoft.Json.JsonConvert.SerializeObject(userEventModel);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    using (var result = await client.PostAsync(url, new StringContent(content, Encoding.UTF8, "application/json")))
                    {
                        string resultContent = await result.Content.ReadAsStringAsync();
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            userEventModel = (UserEventsModel)JsonConvert.DeserializeObject<UserEventsModel>(resultContent);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return userEventModel;
        }
公共静态异步任务GetEvents() { UserEventsModel userEventModel=新的UserEventsModel(); 尝试 { //字符串url=urlstants.GET\u USER\u事件; 字符串url=urlstants.USER\u日记; 使用(var client=new HttpClient()) { client.DefaultRequestHeaders.TryAddWithoutValidation(“Cookie”,LocalDataHelper.RestoreCookie()); string content=Newtonsoft.Json.JsonConvert.SerializeObject(userEventModel); client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”); 使用(var result=await client.PostAsync(url,new-StringContent(content,Encoding.UTF8,“application/json”)) { 字符串resultContent=wait result.Content.ReadAsStringAsync(); if(result.StatusCode==System.Net.HttpStatusCode.OK) { userEventModel=(UserEventsModel)JsonConvert.DeserializeObject(resultContent); } } } } 捕获(例外情况除外) { 投掷; } 返回userEventModel; }
您的类或基类是否实现了INotifyPropertyChanged接口

像这样:

public abstract class BaseViewModel : INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new 
                  PropertyChangedEventArgs(propertyName)); 
        }
 }

 public class YOURViewModel : BaseViewModel
 {
        private string _Hashtag; 
        public string Hashtag
        {
            get { return _Hashtag; }
            set { _Hashtag = value; OnPropertyChanged(); }
        }
 }

根据您的代码,您希望将ViewModel绑定到ListView,首先,您需要知道ListView是集合控件,所以您应该将集合绑定到ListView的itemsource

在您的代码中,您希望使用EventsList绑定ListView,但我看不出您在哪里将数据填充到EventsList

我看到这里有UserEventsModelViewModel和Events集合,但为什么要使用这个集合呢

我将您的Viewmodel更改为为为您制作一个示例,请查看:

public partial class Page9 : ContentPage
{

    public ObservableCollection<UserEventModel> EventsList { get; set; }
    public Page9 ()
    {
        InitializeComponent ();

        //populate data in collection EventsList.
        EventsList = new ObservableCollection<UserEventModel>()
        {
            new UserEventModel(){Hashtag="test1",Rating="test1",mTP=0, Image="test1",Date="test1"}
        };
        this.BindingContext = this;
    }
}

public class UserEventModel
{
    public string Hashtag { get; set; }
    public string Rating { get; set; }
    public decimal? mTP { get; set; }
    public string Image { get; set; }
    public string Date { get; set; }
}
公共部分类第9页:内容页
{
公共ObservableCollection事件列表{get;set;}
公共页9()
{
初始化组件();
//在集合事件列表中填充数据。
EventsList=新的ObservableCollection()
{
新的UserEventModel(){Hashtag=“test1”,Rating=“test1”,mTP=0,Image=“test1”,Date=“test1”}
};
this.BindingContext=this;
}
}
公共类UserEventModel
{
公共字符串哈希标记{get;set;}
公共字符串评级{get;set;}
公共十进制数?mTP{get;set;}
公共字符串图像{get;set;}
公共字符串日期{get;set;}
}
ListView在第9页

   <ListView ItemsSource="{Binding EventsList}"
                  CachingStrategy="RecycleElement"
                  x:Name="EventsDiary"
                  ItemAppearing="EventsDiary_ItemAppearing"
                  SelectionMode="None"
                  HasUnevenRows="True"
                  Margin="0,0,0,10">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <material:MaterialCard HorizontalOptions="FillAndExpand"
                                               VerticalOptions="FillAndExpand"
                                               CornerRadius="2"
                                               Margin="10,0,10,15"
                                               HeightRequest="178"
                                               Padding="0"
                                               BackgroundColor="#f4f4f4">
                            <Grid RowSpacing="0">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="auto" />
                                    <ColumnDefinition Width="auto" />
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="auto" />
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="6" />
                                    <RowDefinition Height="auto" />
                                    <RowDefinition Height="auto" />
                                    <RowDefinition Height="auto" />
                                    <RowDefinition Height="auto" />
                                </Grid.RowDefinitions>
                                <BoxView Grid.Column="0"
                                         Grid.ColumnSpan="5"
                                         Grid.Row="0"  BackgroundColor="{StaticResource CustomizedRedColor}"
                                         CornerRadius="4"
                                         Margin="0" />

                                <RelativeLayout Grid.Column="0"
                                                Grid.Row="1"
                                                Margin="10,10,0,0">
                                    <controls:CircleImage HeightRequest="90"
                                                          WidthRequest="90"
                                                          Source="serpa1.png"
                                                          Aspect="AspectFill">
                                    </controls:CircleImage>

                                    <material:MaterialCard HeightRequest="30"
                                                           WidthRequest="30"
                                                           CornerRadius="50"
                                                           BackgroundColor="#525252"
                                                           Margin="0"
                                                           Padding="0"
                                                           Opacity="0.9">
                                        <Label Text="1"
                                               TextColor="White"
                                               HorizontalOptions="CenterAndExpand"
                                               VerticalOptions="CenterAndExpand" />
                                    </material:MaterialCard>
                                </RelativeLayout>

                                <StackLayout Grid.Column="1"
                                             Grid.ColumnSpan="3"
                                             Grid.Row="1"
                                             Padding="0"
                                             Margin="0"
                                             Orientation="Vertical"
                                             Spacing="0">

                                    <Label Text="Ključne reči"
                                           FontSize="18"
                                           Margin="0,5,0,0"
                                           TextColor="#03414e"
                                           FontFamily="{StaticResource BalooBhai}" />

                                    <Label Text="{Binding Hashtag}"
                                           FontSize="12"
                                           Margin="0"
                                           VerticalOptions="StartAndExpand"
                                           TextColor="#030303" />
                                </StackLayout>
                            </Grid>
                        </material:MaterialCard>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>