Search code examples
wpfdata-bindingdatatemplate

WPF databinding to a list of datetime objects


I have a combo box that I want to bind to a list of datetime objects, but I want to show the datetime objects in short time format. I'm pretty sure I need to use some form of data template for this, but I can't figure out how to bind to the datetime object's ToShortTime method within the data template.

Can someone point me in the right direction?


Solution

  • Assuming you're using .NET 3.0 or 3.5 with SP1, you can simply use the StringFormat to specify the format, for example:

    <TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat='{}{0:t}'}" />
    

    Will show the current date time with short time format ('t' standard date time format modifier, exactly the same as calling DateTime.Now.ToString("t")).

    Edit: If you're already in a data template having a DateTime as the DataContext, just use:

    <TextBlock Text="{Binding StringFormat='{}{0:t}'}" />