zoukankan      html  css  js  c++  java
  • WPF中的数据模板使用方式之一:ContentControl、ContentTemplate和TemplateSelector的使用

    在WPF中,数据模板是非常强大的工具,他是一块定义如何显示绑定的对象的XAML标记。有两种类型的控件支持数据模板:(1)内容控件通过ContentTemplate属性支持数据模板;(2)列表控件通过ItemTemplate属性支持数据模板。为了能够进一步提升数据模板的功能,在使用中常常会要求动态选择数据模板。对于列表控件,可以通过设置DataType来解决,复杂时需要使用模板选择器。以下主要谈论以下内容控件中的模板选择。

            在WPF中,有时内容控件(如ContentControl,Button等)会根据数据对象的类型而需要动态变换,可以使用数据模板配合模板选择器来解决。模板选择器需要从System.Windows.Controls.DataTemplateSelector继承,重写其SelectTemplate方法,在该方法中根据item的类型或item属性来选择合适的数据模板。为了能够选择模板,需要将模板定义为属性,如public DataTemplate BoxGirderTemplate { get; set; }等等。

       public class MyContentTemplateSelector:DataTemplateSelector
        {
            public DataTemplate BoxTemplate { get; set; }
            public DataTemplate SlabTemplate { get; set; }
            public DataTemplate TGirderTemplate { get; set; }
            public override DataTemplate SelectTemplate(object item, DependencyObject container)
            {
                ISec s = (ISec)item;
                if (s!=null&&s.Name == "Box")
                    return BoxGirderTemplate;
                else if (s != null && s.Name == "Slab")
                    return SlabTemplate;
                else if (s != null && s.Name == "TGirder")
                    return TGirderTemplate;
                return null;
            }
        }

    在xaml中,在内容控件中实例化模板选择器。在实例化模板选择器的过程中,将数据模板作为模板选择器的参数注入,代码如下:

                <ContentControl Name="MyContentControl">
                    <ContentControl.ContentTemplateSelector>
                        <local:ElementPropContentTemplateSelector BoxTemplate="{StaticResource BoxGirder}"  SlabTemplate="{StaticResource Slab}"  TGirderTemplate="{StaticResource TGirder}"/>
                    </ContentControl.ContentTemplateSelector>
                </ContentControl>

    此外,在Windows.Resources中,需要定义数据模板,代码如下:

        <Window.Resources>
            <DataTemplate x:Key="BoxGirder">
                <StackPanel >
                         ..........................
                </StackPanel>
            </DataTemplate>
            <DataTemplate x:Key="Slab">
                  <StackPanel >
                         ..........................
                </StackPanel>
            </DataTemplate>
            <DataTemplate x:Key="TGirder">
            <StackPanel >
                         ..........................
                </StackPanel>
            </DataTemplate>

    <Window.Resources>

  • 相关阅读:
    hdfs fsck命令查看HDFS文件对应的文件块信息(Block)和位置信息(Locations)
    更高的压缩比,更好的性能–使用ORC文件格式优化Hive
    InfluxDB基本概念和操作
    InfluxDB部署
    Zookeeper运维小结--CancelledKeyException
    Zookeeper源码编译为Eclipse工程(win7下Ant编译)
    ZooKeeper Observers解决节点过多时写性能下降问题
    ZooKeeper日志与快照文件简单分析
    ZooKeeper Administrator's Guide A Guide to Deployment and Administration(吃别人嚼过的馍没意思,直接看官网资料)
    ZOOKEEPER解惑
  • 原文地址:https://www.cnblogs.com/sjqq/p/8316050.html
Copyright © 2011-2022 走看看