Xamarin Forms的ListView在ItemTemplate中绑定ViewModel变量非集合中的字段

首先定义一个ViewModel

public class Item
    {
        public string Name;
        public string Des;
    }
    public class DemoViewModel:ObservableObject
    {
        string _displayText;
        public string DisplayText
        {
            get
            {
                return _displayText;
            }
            set
            {
                _displayText = value;
                OnPropertyChanged("DisplayText");

            }
        }
        List<Item> _item;
        public List<Item> Items
        {
            get
            {
                return _item;
            }
            set
            {
                _item = value;
                OnPropertyChanged("Items");

            }
        }
        public DemoViewModel()
        {
            DisplayText = "绑定内容在这里";
            Items = new List<Item>();
            Items.Add(new Item { Name = "小明", Des = "班长" });
            Items.Add(new Item { Name = "小红", Des = "组长" });
            Items.Add(new Item { Name = "小亮", Des = "学生" });
        }

 

接着在Page的cs文件中设置绑定

using MyTheme.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace MyTheme.Views
{
  [XamlCompilation(XamlCompilationOptions.Compile)]
  public partial class DemoPage : ContentPage
  {
        DemoViewModel demoViewModel;
        public DemoPage ()
    {
      InitializeComponent ();
            demoViewModel = new DemoViewModel();
            BindingContext = demoViewModel;

        }
  }
}

 

在xaml中给Page添加x:Name以及绑定字段

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Name="DemoPage" xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyTheme.Views.DemoPage" >
    <ContentPage.Content>
        <StackLayout>
            <ListView ItemsSource="{Binding Items}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Label  Text="{Binding Name}"/>
                        <Label  Text="{Binding Path=BindingContext.DisplayText, Source={x:Reference Name=DemoPage}}"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
                    
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

 

原创文章,转载请注明本文链接地址(违者必究):Xamarin Forms的ListView在ItemTemplate中绑定ViewModel变量非集合中的字段

打赏作者
很喜欢这篇文章,打赏犒劳下作者,以此激励作者创作更多

您的支持将鼓励我们继续创作!

[微信] 扫描二维码打赏

[支付宝] 扫描二维码打赏