一.XML

<Page
x:Class="MVVM.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MVVM"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" > <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="120*"></RowDefinition>
<RowDefinition Height="500*"></RowDefinition> </Grid.RowDefinitions>
<!--<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>-->
<StackPanel Grid.Row="0">
//绑定数据源 绑定的事viewModel的公有字段
<TextBlock Text="{Binding Path=Title1}" FontSize="30"></TextBlock>
<TextBlock Text="{Binding Path=Title2}" FontSize="60"></TextBlock> </StackPanel>
<Grid x:Name="contentRoot"/>
<ListView Grid.Row="1" ItemsSource="{Binding Collection}" Margin="10,10,-10,10">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" FontSize="40" Margin="0 ,0,20,0" />
<TextBlock Text="{Binding Gender}" FontSize="40" Margin="0 ,0,20,0" />
<TextBlock Text="{Binding Age}" FontSize="40" Margin="0 ,0,20,0" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page> 二、Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MVVM
{
public class PersonModel
{
public string Name { get; set; }
public char Gender { get; set; }
public int Age { get; set; }
}
}

三、ViewModel

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MVVM
{
//要实现通知 ——>就要实现INotifyPropertyChanged
public class PersonViewModel:INotifyPropertyChanged
{
private string title1;
private string title2;
public PersonViewModel(){}
public PersonViewModel(string Title1, string Title2, IEnumerable<PersonModel> collection)
{
this.title1 = Title1;
this.title2 = Title2;
Collection = new ObservableCollection<PersonModel>();
foreach (var item in collection)
{
Collection.Add(item); } }
//实现接口 + 处理方法
public event PropertyChangedEventHandler PropertyChanged;
private void EventHendle(string propertyNanme)
{
if (PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs (propertyNanme));
}
} public string Title1 { get { return title1; }set { Title1 = value;EventHendle(Title1);}}
public string Title2 { get{return title2;} set{Title2=title2;EventHendle(Title2);}} public ObservableCollection<PersonModel> Collection { get; set; } }
}
结果如下:

MVVM 代码记录-LMLPHP

MVVM代码记录,来自传智播客公开课

05-07 15:15