绑定字符串格式给出不正确的结果
本文关键字:不正确 结果 字符串 格式 绑定 | 更新日期: 2023-09-27 18:35:07
出于某种原因,使用Content="{Binding Time, StringFormat=t}
仍然给了我一个很长的日期。支持字段是用 DateTime.Now
初始化的 DateTime
属性,但无论我尝试哪种字符串格式,它仍然显示完整日期......
我只想看到 HH:mm tt
有什么想法吗?
XAML :
<Window x:Class="ArgosSystem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:ArgosSystem"
xmlns:sys="clr-namespace:System;assembly=System"
Title="MainWindow" Height="800" Width="1280" Loaded="Window_Loaded">
<Window.Resources>
<DataTemplate DataType="{x:Type loc:Picknote}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" MinWidth="200" />
<ColumnDefinition Width="350" />
<ColumnDefinition Width="250" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Label Content="{Binding Time, StringFormat=t}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="0" />
<Label Content="{Binding Customer}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="1" />
<Label Content="{Binding PicknoteNo}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="2" />
<Label Content="{Binding Qty}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="3" />
</Grid>
</DataTemplate>
</Window.Resources>
<Grid Background="Black">
<DockPanel>
<ScrollViewer Name="lstPicknoteScroll" VerticalScrollBarVisibility="Auto">
<ItemsControl Name="lstPicknotes" ItemsSource="{Binding}" IsTabStop="False" Foreground="Cornsilk" />
</ScrollViewer>
</DockPanel>
</Grid>
</Window>
C# :
public partial class MainWindow : Window
{
ObservableCollection<Picknote> picknotes = new ObservableCollection<Picknote>();
public MainWindow()
{
InitializeComponent();
lstPicknotes.DataContext = picknotes;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
picknotes.Add(new Picknote
{
Time = DateTime.Now,
Customer = "REED FOR SPEED",
PicknoteNo = "PKN767677",
Qty = 100
});
picknotes.Add(new Picknote
{
Time = DateTime.Now.AddHours(-2),
Customer = "F1 AUTOMOTIVE",
PicknoteNo = "PKN767677",
Qty = 50
});
picknotes.Add(new Picknote
{
Time = DateTime.Now.AddHours(-1),
Customer = "FERGUSENS",
PicknoteNo = "PKN767677",
Qty = 10
});
}
}
StringFormat 适用于字符串类型的属性。内容属性的类型为"对象",因此需要使用"标签"控件的"内容字符串格式"属性指定格式。
<Label Content="{Binding Time}" ContentStringFormat="t" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="0" />