最近在使用wpf的时候,遇到某个列的值需要根据内容不同进行转换显示的需求。尝试了一下,大概有三种方式可以实现:

1、传统的binding方法,后台构造好数据,绑定就行。

2、转换器方法(converter),绑定后,触发转换器,转换器负责把值转换成需要的内容。

3、datatrigger方法,直接在xaml里面对数据进行处理,展示所需要的内容。

这里主要学习了怎么使用第3种方法。写下来,防止突然想找的时候还得去翻源码。

<datagridtemplatecolumn header="数据包是否下载" width="140">
    <datagridtemplatecolumn.celltemplate>
        <datatemplate>
            <textblock>
                <textblock.style>
                    <style targettype="textblock" basedon="{staticresource textblockbasestyle}">
                        <style.triggers>
                            <datatrigger binding="{binding path= devisdownload}" value="false">
                                <setter property="text"  value="否"></setter>
                                <setter property="foreground" value="red"></setter>
                            </datatrigger>
                            <datatrigger binding="{binding path= devisdownload}" value="true">
                                <setter property="text"  value="是"></setter>
                                <setter property="foreground" value="green"></setter>
                            </datatrigger>
                        </style.triggers>
                    </style>
                </textblock.style>
            </textblock>
        </datatemplate>
    </datagridtemplatecolumn.celltemplate>
</datagridtemplatecolumn>

根据绑定的devisdownload列的内容(bool类型),来触发显示效果,如果为false,则前台显示为 红色的“否”字。如果为true,则前台显示为 绿色的“是”字。