相同的绑定,不同的演示?

时间:2012-07-08 11:33:34

标签: .net wpf data-binding

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <System:DateTime x:Key="d" >2012/7/8</System:DateTime>
    </Window.Resources>
    <StackPanel>
        <ContentControl Content="{Binding}" DataContext="{StaticResource d}" />
        <TextBlock Text="{Binding}" DataContext="{StaticResource d}"/>
    </StackPanel>
</Window>

此代码为我提供了以下窗口。

enter image description here

奇怪的是,适用于ContentControl的相同绑定仅显示日期部分,适用于TextBlock时也显示时间部分。

我只是想知道原因并询问是否可以交换演示文稿,我的意思是TextBlock只显示日期部分而ContentControl显示这两部分。

谢谢。

1 个答案:

答案 0 :(得分:3)

对于ContentControl,请使用ContentStringFormat。对于TextBlock,请使用BindingStringFormat

<ContentControl Content="{Binding}" ContentStringFormat="dd/MM/yyyy HH:mm:ss"/>
<TextBlock Text="{Binding ., StringFormat=dd/MM/yyyy}"/>

简而言之,差异可归结为ContentControl可以将任何旧的object显示为内容(而不仅仅是string),而TextBlock.Text只能是string

相关问题