WPF 19(绑定2-绑定资源模板)

来源:互联网 发布:战区 知乎 编辑:程序博客网 时间:2024/05/16 14:36

上一节我们了解到绑定的方式,下面我们来了解下资源模板的绑定。

我们先定义一个Person类(Person.cs),比如他有PersonName属性,可以实现变更通知。(Person.cs)

public class Person : INotifyPropertyChanged    {        private string name;        public event PropertyChangedEventHandler PropertyChanged;        public Person()        {        }        public Person(string value)        {            this.name = value;        }        public string PersonName        {            get { return name; }            set            {                name = value;                OnPropertyChanged("PersonName");            }        }        protected void OnPropertyChanged(string name)        {            PropertyChangedEventHandler handler = PropertyChanged;            if (handler != null)            {                handler(this, new PropertyChangedEventArgs(name));            }        }

我们给它一些 静态的数据。

首先我们新建一个.cs文件叫 Datas.cs吧。里面是:

  public class Datas : List<Person>    {        public Datas()        {            Add(new Person("张三"));            Add(new Person("李四"));            Add(new Person("王五"));        }    }

后台都准备好了,我们就开始前台吧。

先在xaml中添加

xmlns:local="clr-namespace:Demo"

这里的Demo是项目的名称,即命名空间的名称。这是为我们引用刚才新建的两个类文件用的。

看下面Xaml代码。

 <Grid>        <Grid.Resources>            <local:Datas x:Key="listBoxData"/>            <DataTemplate x:Key="listBoxDataTemplate">                <TextBlock Text="{Binding PersonName}"/>            </DataTemplate>        </Grid.Resources>        <ListBox ItemTemplate="{StaticResource listBoxDataTemplate}"                  ItemsSource="{StaticResource listBoxData}">        </ListBox>    </Grid>

DataTemplate是: 来指定数据对象的可视化。
ItemTemplate是:获取或设置用于显示每个项的 DataTemplate。
ItemsSource是:获取或设置用于生成 ItemsControl 的内容的集合。
运行结果:

image

我们可以在给他添点样式。比如在DataTemplate里

<DataTemplate x:Key="listBoxDataTemplate">                <TextBlock Text="{Binding PersonName}"              FontSize="32" FontStyle="Oblique" Foreground="Blue"/></DataTemplate>

结果:

image

0 0
原创粉丝点击