我一直在玩 WPF
有一段时间了,我遇到了一件有趣的事情。当我将 DateTime
对象绑定(bind)到 Label
的内容时,我会看到日期的本地格式表示。但是,当我绑定(bind)到 TextBlock
的 Text 属性时,我实际上看到的是英文。
似乎 TextBlock
正在使用某种转换器,而 Label
只是调用 ToString
方法,但我不确定。
如果是这样,为什么 Label
不也使用转换器?
为什么会这样?我提供一个简短的示例,让你们检查发生了什么:
// MainWindow.xaml
<Window x:Class="BindConversion.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel HorizontalAlignment="Center" Margin="3">
<StackPanel>
<Label Content="{Binding Dt}"/>
<TextBlock Text="{Binding Dt}"/>
</StackPanel>
</StackPanel>
</Window>
// MainWindow.xaml.cs
using System;
using System.Windows;
namespace BindConversion
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public DateTime Dt { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
Dt = DateTime.Now;
}
}
}
最佳答案
如果您仔细查看 Label
,您会发现它派生自 ContentControl
。
Content
属性由 ContentPresenter
显示,在文档中是这样说的:
如果存在将 Content 类型转换为 UIElement 的 TypeConverter,ContentPresenter 将使用该 TypeConverter 并显示生成的 UIElement。
现在有一个 DateTimeConverter
继承自 TypeConverter
,下面的代码片段生成与 Label
完全相同的字符串:
var dateTimeConverter = new DateTimeConverter();
var convertToString = dateTimeConverter.ConvertToString(DateTime.Now);
引用资料:
https://msdn.microsoft.com/en-us/library/system.windows.controls.contentpresenter(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.componentmodel.datetimeconverter(v=vs.110).aspx
关于c# - Label 和 TextBlock 的文化差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39172824/