La cosa bella di StringFormat
è che permette di specificare il formato dell'output. Ecco un convertitore che uso che ti permette di specificare il formato.
public sealed class DateTimeToStringConverter : IValueConverter
{
public static readonly DependencyProperty FormatProperty =
DependencyProperty.Register(nameof(Format), typeof(bool), typeof(DateTimeToStringConverter), new PropertyMetadata("G"));
public string Format { get; set; }
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is DateTime dateTime && value != null)
{
return dateTime.ToString(Format);
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return DateTime.ParseExact(value.ToString(), Format, CultureInfo.CurrentCulture);
}
}
Come utilizzare (ad esempio con diversi formati):
<Page.Resources>
<ResourceDictionary>
<converters:DateTimeToStringConverter
x:Name="dateStringConverter"
Format="dd-MM-yyyy" />
<converters:DateTimeToStringConverter
x:Name="timeStringConverter"
Format="HH:mm" />
</ResourceDictionary>
</Page.Resources>
<!-- Display the date -->
<TextBlock Text="{Binding Path=Date, Converter={StaticResource dateStringConverter}}" />
<!-- Display the time -->
<TextBlock Text="{Binding Path=Date, Converter={StaticResource timeStringConverter}}" />
Non funziona. Errore: la risorsa "DateStringToFormatConverter" non può essere risolta. – developer033
Devi dichiarare il convertitore nel tuo xaml per usarlo – CodeNoob
Se potessi modificare la tua risposta a una risposta completa, sarebbe grandioso. – developer033