1, 建立WPF程序,并在程序中添加三个文件View,ViewMoudle,Moudle,
2,Moudle文件加中添加类,此文件夹中存放的类基本为数据类,主要是字段和属性
3 ViewMoudle文件加中添加类,首先添加一个基类作为ViewMoudle中所有类的父类,
这个类继承INotifyPropertyChanged,只用简单实现此接口的事件
代码如下
public class ViewMoudleBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
}
}
之后,是集成Moudle中的结构类,并在此写逻辑代码,此处只简介绑定的用法
列如Moudle中有个Person类
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
}
我们可以在ViewMoudle中添加一个PageViewModel
public class PageViewModel:ViewMoudleBase
{
private ObservableCollection<Person> human = null;
public ObservableCollection<Person> Human
{
get
{
return human;
}
set
{
human = value;
当用list等其他集合是写下面的红色加粗部门,
if (human!=value)
{
human = value;
OnPropertyChanged("Human");
}
}
}
public PageViewModel()
{
human = new ObservableCollection<Person>();
Human.Add( new Person{Name = "Tom",Age = 21 });
Human.Add(new Person { Name = "Jack", Age = 22 });
Human.Add( new Person{Name = "Rose",Age = 23 });
}
}
(注意加粗的地方,如果改为一般的集合例如List类,就不能实现动态的在UI界面添加数 据了,原因是ObservableCollection继承了INotifyPropertyChanged)
4 View中添加窗口,在Xaml页面中通过Bing绑定相应的类以及字段
例如
<DataGrid AutoGenerateColumns="False" Height="200" ItemsSource="{Binding Human}" HorizontalAlignment="Left" Margin="34,20,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="516" Grid.RowSpan="2">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Height="23" HorizontalAlignment="Left" Name="textBlock1" Text="{Binding Name}" VerticalAlignment="Top" />
<TextBlock Height="23" HorizontalAlignment="Left" Name="textBlock2" Text="{Binding Age}" VerticalAlignment="Top" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
在CS页面实现,通过 DataContext 实现View与ViewMoudle的绑定,
代码如下
public partial class PageView : Window
{
public PageViewModel vm ;
public PageView()
{
InitializeComponent();
vm=new PageViewModel();
vm.Human.Add(new Person { Name = "闪灵", Age = 1 });
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Dispatcher.BeginInvoke(new Action(() =>
{
vm.Human.Add(new Person { Name = "闪灵45", Age = 1 });
}));
}
}