110,536
社区成员
发帖
与我相关
我的任务
分享
前台
<ListView x:Name="listview">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Number}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
后台
listview.ItemsSource = GameCardService;
using System;
using System.ComponentModel;
namespace WpfApplication2
{
public class GameCard : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void PropertyChangedNotify(string propName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
private String number;
public String Number
{
set
{
Number = value;
}
get
{
return number;
}
}
public GameCard(string _number)
{
number = _number;
}
}
}
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace WpfApplication2
{
public class GameCardService : ObservableCollection<GameCard>, INotifyPropertyChanged
{
public GameCardService()
: base()
{
for (int i = 0; i < 54; i++)
Add(new GameCard("Number" + i));
}
public void setNumbers(int[] _Number)
{
for (int i = 0; i < 54; i++)
{
this[i].Number = _Number[i].ToString();
}
}
}
}
接下来,因为我们要使用窗体MainWindow来显示它,所以自然地,定义一个对应的VM类
namespace WpfApplication2
{
public class MainWindowModel
{
public MainWindowModel()
{
this.PGameCard = new GameCardService();
}
public GameCardService PGameCard { get; set; }
}
}
最后就是最终目的——View类<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowModel />
</Window.DataContext>
<Grid>
<TextBlock Text="{Binding PGameCard[0].Number}" />
</Grid>
</Window>
我首先会把 MainWindow.xaml.cs 文件删除。因为只有这样,才可以真正比较严格地使用 MVVM 模式。