绑定资源模板

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

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

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吧。里面是:

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>
在资源里,这里listBoxData是下面引用的key值,DataTemplate是数据模板。

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

MSDN 教程短片 WPF 19(绑定2-绑定资源模板)

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

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

结果:

MSDN 教程短片 WPF 19(绑定2-绑定资源模板)

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
  • 2022-12-23
  • 2021-10-16
  • 2021-06-15
  • 2022-12-23
猜你喜欢
  • 2022-02-17
  • 2021-10-31
  • 2021-06-01
  • 2021-09-08
  • 2021-05-28
  • 2021-12-13
  • 2022-12-23
相关资源
相似解决方案