zoukankan      html  css  js  c++  java
  • WPF:在DataTemplate中使用DataType

    DataTemplate中的DataType的功能实际上和Style中的TargetType很类似。

    在Style中,使用了TargetType之后,如果不定义Style的Key,那么这个Style将会影响到它所在区域的所有TargetType控件的样式。

    同理,在DataTemplate中,使用了DataType之后,如果不定义DataTemplate的Key,那么这个DataTemplate将应用于它所在区域,所有的以这个DataType为数据源的控件。

    我写了一个小例子来展示这个效果。

    定义Model,Person:

        public class Person
        {
            public string Name
            {
                get;
                set;
            }
    
            public int Age
            {
                get;
                set;
            }
        }

    定义ViewModel:

        public class MainViewModel
        {
            public ObservableCollection<Person> AllPerson
            {
                get;
                set;
            }
    
            public MainViewModel()
            {
                AllPerson = new ObservableCollection<Person>
                {
                    new Person
                    {
                        Name = "张三",
                        Age = 18
                    },
                    new Person
                    {
                        Name = "李四",
                        Age = 28
                    }
                };
            }
        }

    定义DataTemplate,使用了DataType:

        <Window.Resources>
            <DataTemplate DataType="{x:Type local:Person}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                    <TextBlock Text="{Binding Age}" />
                </StackPanel>
            </DataTemplate>
        </Window.Resources>

    ItemControl的ItemTemplate使用上面定义的DataTemplate:

            <ItemsControl ItemsSource="{Binding AllPerson}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Vertical" />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>

    由于ItemControl的Item的数据源为Person,且存在具有Person为DataType的DataTemplate,所以ItemControl的ItemTemplate会自动应用上面定义的DataTemplate。

    运行效果如下:

  • 相关阅读:
    redis 写入数据 越来越慢 是什么原因
    redis slowlog
    JavaCC 规格严格
    Lucene 规格严格
    数据库建立索引要点 规格严格
    编辑距离 规格严格
    Lucene NRT (Near Real Time) 规格严格
    事件关联 规格严格
    linux下mysql5.5.19编译安装笔记【已验证】 规格严格
    关于CLOSE BY CLIENT STACK TRACE 规格严格
  • 原文地址:https://www.cnblogs.com/DoNetCoder/p/4385257.html
Copyright © 2011-2022 走看看