2016-01-11 12 views
15

Vista:StringFormat su Binding

<TextBlock Text="{Binding Date}"/> 

voglio formattare la data a "dd/MM/yyyy", in altre parole, senza il tempo.

L'ho provato: <TextBlock Text="{Binding Date, StringFormat={}{0:dd/MM/yyyy}}"/>, ma non funziona.

Mi dà un errore: la proprietà 'StringFormat' non è stata trovata nel tipo 'Binding'.

risposta

16

Il modo migliore e più semplice sarebbe quello di utilizzare un convertitore a cui si passa la data e recuperare la stringa formattata. Ad es. MyNamespace.Converters namespace:

public class DateFormatConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, string language) 
    { 
     if (value == null) 
      return null; 

     DateTime dt = DateTime.Parse(value.ToString()); 
     return dt.ToString("dd/MM/yyyy"); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 

E nel tuo XAML solo riferimento il convertitore e aggiungere il seguente convertitore:

xmlns:conv="using:MyNamespace.Converters" 

nella tua pagina XAML e in page.resources aggiungere questo

<conv:DateFormatConverter x:Name="DateToStringFormatConverter"/> 

<TextBlock Text="{Binding Date, Converter={StaticResource DateToStringFormatConverter}"/> 
+0

Non funziona. Errore: la risorsa "DateStringToFormatConverter" non può essere risolta. – developer033

+0

Devi dichiarare il convertitore nel tuo xaml per usarlo – CodeNoob

+0

Se potessi modificare la tua risposta a una risposta completa, sarebbe grandioso. – developer033

4

Ci non è una proprietà denominata StringFormat nella classe Binding. È possibile utilizzare Converter e ConverterParameter per farlo. È possibile fare riferimento a Formatting or converting data values for display.

Per esempio qui, lego la data di un DatePicker al testo di un TextBlock.

XAML:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
    <Grid.Resources> 
     <local:DateFormatter x:Key="DateConverter"/> 
    </Grid.Resources> 
    <DatePicker Name="ConverterParmeterCalendarViewDayItem"></DatePicker> 
    <TextBlock Height="100" VerticalAlignment="Top" Text="{Binding ElementName=ConverterParmeterCalendarViewDayItem, Path=Date, Converter={StaticResource DateConverter},ConverterParameter=\{0:dd/MM/yyyy\}}" /> 
</Grid> 

codice dietro, la classe DateFormatter:

public class DateFormatter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, string language) 
    { 
     var a = language; 
     // Retrieve the format string and use it to format the value. 
     string formatString = parameter as string; 
     if (!string.IsNullOrEmpty(formatString)) 
     { 
      return string.Format(formatString, value); 
     } 

     return value.ToString(); 
    } 

    // No need to implement converting back on a one-way binding 
    public object ConvertBack(object value, Type targetType, object parameter, string language) 
    { 
     return DependencyProperty.UnsetValue; 
    } 
} 
+0

È venuto a dare esattamente la stessa risposta. Il modo migliore che si può fare è con un convertitore, come mostrato sopra, a meno che non si cambi la data in una stringa in code-behind e si formatti lì invece. [Informazioni sui formati DateTime] (https://msdn.microsoft.com/en-us/library/az4se3k1 (v = vs.110) .aspx) –

+0

Sfortunatamente, non funziona qui ... Il tipo ' local: DateFormatter 'non è stato trovato. Cosa mi manca? – developer033

+0

È necessario creare una classe denominata DateFormatter, vedere la mia classe 'DateFormatter'. –

1

C'è un ottimo esempio qui:

Example from MSDN

Se la classe convertitore è in una spazio dei nomi diverso (come suggerito per essere in una cartella separata R) è possibile aggiungere

xmlns:conv="using:MyNamespace.Converters" 

e usarlo in questo modo:

<UserControl.Resources> 
    <conv:DateToStringConverter x:Key="Converter1"/> 
</UserControl.Resources> 

il resto dovrebbe rimanere lo stesso, come nell'esempio dal link.

2

perché complicare? È possibile utilizzare i dati compilati binding

{x:Bind ViewModel.PropertyWithDateTime.ToString("....")} 
0

So che questo è in ritardo ma ho avuto la stessa domanda e si avvicinò con questa soluzione. Forse non il più breve ma puro XAML.

<TextBlock> 
     <Run Text="{x:Bind Foo.StartDate.Day}"/>.<Run Text="{x:Bind Foo.StartDate.Month}"/>.<Run Text="{x:Bind Foo.StartDate.Year}"/> 
    </TextBlock> 
0

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}}" /> 
0

Prova questa,

<Label x:Name="LblEstEndTime" Text="{Binding EndTime, StringFormat='Est. End Time: {0:MM/dd/yy h:mm tt}'}" Style="{StaticResource ListCellSubTitleStyle}" VerticalOptions="EndAndExpand" /> 

+1

Anche se le risposte al solo codice possono risolvere il problema originale, alcune spiegazioni potrebbero aiutare molto nella comprensione del metodo che hai usato e di come funziona. –

Problemi correlati