如何更改日期格式

时间:2018-10-05 15:02:36

标签: c# xamarin xamarin.forms

我收到的日期为2018-10-03格式,我想切换为03/10/2018

<Label Text="{Binding cmPaymentDate, StringFormat='{0:dd/MM/yyyy}'}"  TextColor="White" Font="14"/>

1 个答案:

答案 0 :(得分:0)

您可以尝试使用转换器。另一件事是,它必须是一个DateTime,否则stringFormat无效。

<Window x:Class="StackPoC.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"
    xmlns:local="clr-namespace:StackPoC"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<StackPanel>
    <StackPanel.Resources>
        <local:DateConverter x:Key="DateConverter" />
    </StackPanel.Resources>
    <TextBlock Text="{Binding CmPaymentDate, Converter={StaticResource DateConverter}}"  Foreground="Black" FontSize="14"/>
</StackPanel>

隐藏代码

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private DateTime _cmPaymentDate;
    public DateTime CmPaymentDate
    {
        get
        {
            return _cmPaymentDate;
        }
        set
        {
            _cmPaymentDate = value;
            OnPropertyChanged("CmPaymentDate");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;

        CmPaymentDate = new DateTime(2018, 09, 23);
    }

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

和转换器:

public class DateConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        DateTime dt = (DateTime)value;
        return dt.ToString("dd/MM/yyyy");
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}