1
<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>

这段代码给了我以下窗口。

在此处输入图像描述

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

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

谢谢你。

4

1 回答 1

3

对于ContentControl,使用ContentStringFormat。对于TextBlock,使用 aBinding和 a StringFormat

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

简而言之,区别在于 aContentControl可以将任何旧的内容显示object为内容(不仅仅是 a string),而TextBlock.Text只能是 a string

于 2012-07-08T11:38:52.580 回答