• WPF Knowledge Points Binding.StringFormat不起作用的原理和解决


    引出问题

    我们先用一个简单的例子引出问题:有一个DateTime资源,分别用TextBox,Label显示这个DateTime。

    <Grid>
    <Grid.Resources>
    <sys:DateTime x:Key="DateTime001">03/29/2012 15:05:30</sys:DateTime>
    </Grid.Resources>
    <TextBox Text="{Binding Source={StaticResource DateTime001},StringFormat=dddd , Mode=OneWay}"
    Height
    ="23" HorizontalAlignment="Left" Margin="28,68,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
    <Label Content="{Binding Source={StaticResource DateTime001}, StringFormat=dddd, Mode=OneWay}"
    Height
    ="28" HorizontalAlignment="Left" Margin="28,26,0,0" Name="label1" VerticalAlignment="Top" Width="120" />
    </Grid>

    运行结果如图:

    TextBox按照预期的,显示了完整的英文星期,但是Label的格式没有任何改变。我们用了完全一样的Binding和格式字符串,区别究竟在什么地方?如果够细心的话可以发现,TextBox的Binding是在Text属性上进行的,而Label的Binding是在Content属性上进行的。

    详细分析

    本质原因:Control.Content是Object类型,而Binding.StringFormat仅仅在Binding的Property类型为string的时候才有效。

    通过下面Label的Binding流程(来源于Stackoverflow牛人),我们可以看到底层的细节:
    1. Binding把DateTime类型的值装箱,赋值给Label.Content.
    2. Label的Template包含ContentPresenter,用来显示内容。
    3. Label的ContentPresenter会会依次寻找ContentTemplate,DataTemplate去显示内容,当而这都没有找到的时候,它会用默认的Template。
    4. ContentPresenter使用的默认Template用Label.ContentStringFormat属性去格式化object到string。
    5. 注意,以上是简化的流程,本质的,ContentPresenter会用自身的Template和StringFormat显示结果,但是由于在Label控件装载过程中,会自动把Label的ContentTemplate和ContentStringFormat对应绑定到ContentPresenter的ContentTemplate和StringFormat。ContentPresenter本质会优先用Label的ContentTemplate和ContentStringFormat显示。所以,我们这里说CotentPresenter用Label的Properties做显示也没有问题。

    所以,对于非String类型的Content来说,添加属性定义ContentStringFormat=dddd就可以显示我们需要的结果了。

  • 相关阅读:
    解决maven构建webapp index.jsp报错问题
    Maven入门介绍
    Linux常用命令的解释
    linux怎么查看一个文件夹的大小
    EPEL源-是什么全称
    nginx+php-fpm配置后页面显示空白的解决方法(yum形式的安装)
    配置新服务器 的一些 依赖库 php mysql nginx
    服务器 CentOS上yum安装Nginx服务
    Java File创建新目录和文件
    struts2的文件上传
  • 原文地址:https://www.cnblogs.com/KeithWang/p/2423572.html
Copyright © 2020-2023  润新知