首先是设置资源如下:
导入资源名称空间
<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">
- <wpf:Person Name="FirstName" LastName="Last" x:Key="per"/>
绑定的对象,主要将PersonList属性绑定到Text上:
- <TextBlock Text="{Binding Source={StaticResource per},Path=PersonList[1].Name}" />
自定义对象如下:
- public class Person : INotifyPropertyChanged
- {
- private string name;
- public string Name
- {
- get { return name; }
- set { name = value;
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs("Name"));
- }
- }
- }
- private string lastName;
- public string LastName
- {
- get { return lastName; }
- set
- {
- lastName = value;
- }
- }
- private List<Person> personList;
- public List<Person> PersonList
- {
- get { return personList; }
- set
- {
- personList = value;
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs("PersonList"));
- }
- }
- }
- public event PropertyChangedEventHandler PropertyChanged;
- }
当前资源里面的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。
- <TextBlock Text="{Binding Source={StaticResource per},Path=PersonList/Name}" />
当Path改成如上形式,会显示Jay, “/”默认取集合的第一条数据。