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

首先是设置资源如下:

导入资源名称空间

<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 plain copy
  1. <wpf:Person Name="FirstName" LastName="Last" x:Key="per"/>  

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

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


自定义对象如下:

[csharp]  view plain copy
  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 plain copy
  1. <TextBlock Text="{Binding Source={StaticResource per},Path=PersonList/Name}"  />  

当Path改成如上形式,会显示Jay, “/”默认取集合的第一条数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值