WPF使用资源绑定自定义类型

来源:互联网 发布:游戏编程入门 李军 pdf 编辑:程序博客网 时间:2024/05/22 03:14

首先是设置资源如下:

导入资源名称空间

<Window x:Class="BindSelfResource.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"         xmlns:wpf="clr-namespace:BindSelfResource"        Title="MainWindow" Height="350" Width="525">


[csharp] view plaincopy
  1. <wpf:Person Name="FirstName" LastName="Last" x:Key="per"/>  

绑定的对象,主要将PersonList属性绑定到Text上:

[csharp] view plaincopy
  1. <TextBlock Text="{Binding Source={StaticResource per},Path=PersonList[1].Name}"  />  


自定义对象如下:

[csharp] view plaincopy
  1. public class Person : INotifyPropertyChanged  
  2.    {  
  3.        private string name;  
  4.   
  5.        public string Name  
  6.        {  
  7.            get { return name; }  
  8.            set { name = value;  
  9.            if (PropertyChanged != null)  
  10.            {  
  11.                PropertyChanged(thisnew PropertyChangedEventArgs("Name"));  
  12.            }  
  13.            }  
  14.        }  
  15.        private string lastName;  
  16.   
  17.        public string LastName  
  18.        {  
  19.            get { return lastName; }  
  20.            set  
  21.            {  
  22.                lastName = value;  
  23.   
  24.            }  
  25.        }  
  26.   
  27.        private List<Person> personList;  
  28.   
  29.        public List<Person> PersonList  
  30.        {  
  31.            get { return personList; }  
  32.            set  
  33.            {  
  34.                personList = value;  
  35.                if (PropertyChanged != null)  
  36.                {  
  37.                    PropertyChanged(thisnew PropertyChangedEventArgs("PersonList"));  
  38.                }  
  39.            }  
  40.        }  
  41.   
  42.        public event PropertyChangedEventHandler PropertyChanged;  
  43.    }  

当前资源里面的PersonList属性是Null,所以在某个时机下你需要设置值,才能显示TextBlock的Text值,本例我在一个Button事件中设置了值如下:

  Person p = this.FindResource("per") as Person;
  p.PersonList= new List<Person>() { new Person { Name = "Jay", LastName = "Jay" }, new Person { Name = "Jay1", LastName = "Jay1" }, new Person { Name = "Jay2", LastName = "Jay2" } };

单击Button后Text显示Jay1。


[html] view plaincopy
  1. <TextBlock Text="{Binding Source={StaticResource per},Path=PersonList/Name}"  />  

当Path改成如上形式,会显示Jay,“/”默认取集合的第一条数据。
原创粉丝点击