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

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

我们先定义一个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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值