StringFormat on Binding

后端 未结 9 632
野的像风
野的像风 2021-01-01 13:17

View:


I want to format the Date to \"dd/MM/yyyy\", in other words, without the time.

I

9条回答
  •  孤独总比滥情好
    2021-01-01 13:37

    The nice thing about StringFormat is that it allows you to specify the format of the output. Here is a converter I use that allows you to specify the format.

    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);
        }
    }
    

    How to use (example with multiple formats):

    
        
            
            
        
    
    
    
        
    
    
    
    

提交回复
热议问题