Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use StringFormat in XAML elements?

I haven't tested it, but I think this should work:

<GridViewColumn
    Header="Order Date"
    DisplayMemberBinding=
        "{Binding Path=OrderDate, StringFormat='{}{0:dd.MM.yyyy}'}"/>

In general, you can look for an associated *StringFormat dependency property. For example, all ContentControl implementations (such as Label and Tooltip) have the ContentStringFormat dependency property:

<Label
    Content="{Binding Path=DateAsked}"
    ContentStringFormat="{}{0:yyyy/MM/dd HH:mm:ss}" />

In your case, while the GridViewColumn has the HeaderStringFormat dependency property to go along with Header, there is no analog for the DisplayMemberBinding and so you will need .NET 3.5 SP1 (get it with Visual Studio 2008 SP1) or better to use the new BindingBase.StringFormat Property:

<GridViewColumn 
    Header="Order ID"
    DisplayMemberBinding="{Binding Path=OrderID, StringFormat='{}{0:dd.MM.yyyy}'}"
/>

There are lots more examples at the blog post Trying out Binding.StringFormat.


XAML

<UserControl.Resources>
    <myNamespace:DateTimeConverter x:Key="DateTimeConverter" />
</UserControl.Resources>

<GridViewColumn 
DisplayMemberBinding=="{Binding Path=OrderDate, Converter={StaticResource DateTimeConverter}}" 
/>

C#

public class DateTimeConverter : IValueConverter
{
    public object Convert(object value,
                       Type targetType,
                       object parameter,
                       CultureInfo culture)
    {
        if (value != null)
        {
            return ((DateTime)value).ToString("dd.MM.yyyy");
        }
        else
        {
            return String.Empty;
        }
    }

    public object ConvertBack(object value,
                              Type targetType,
                              object parameter,
                              CultureInfo culture)
    {
        return DateTime.Parse(value.ToString());
    }
}