Friday, 13 September 2013

Setting format for Telerik RadDatePicker

First up remember there are two date pickers the RadDatePicker and the RadDateTimePicker.

You can specialise with your date hardcoded, or have a property that lets the developer set the value:

public class RadDatePickerWithSwissDates : RadDatePicker
{
public RadDatePickerWithSwissDates()
{
var ci = new CultureInfo("")
{
DateTimeFormat = { ShortDatePattern = "dd.MM.yyyy" }
};

this.Culture = ci;
}
}

Or you can use this approach:

public class TelerikDateFormatWorkaround
{
public CultureInfo CultureWithSwissFormat
{
//Hack to get around the fact that there is no custom date format in the Telerik DatePicker
//http://www.telerik.com/community/forums/wpf/datepicker/changing-dateformat.aspx
get
{
var tempCultureInfo = (CultureInfo)CultureInfo.CurrentCulture.Clone();
tempCultureInfo.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
return tempCultureInfo;
}
}
}

// add it to the usercontrol resources in the usual way and then...

<Style TargetType="telerik1:RadDatePicker">
<Setter Property="Culture" Value="{Binding Source={StaticResource TelerikDateFormatWorkaround}, Path=CultureWithSwissFormat}"/>
</Style>

BooleanToVisibilityConverterMarkupExtension

public class BooleanToVisibilityConverterMarkupExtension : MarkupExtension, IValueConverter
{
private static BooleanToVisibilityConverterMarkupExtension converter;

public override object ProvideValue(IServiceProvider serviceProvider)
{
return converter ?? (converter = new BooleanToVisibilityConverterMarkupExtension());
}

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var v = (bool?)value;
return v.HasValue && v.Value ? Visibility.Visible : Visibility.Collapsed;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var v = (Visibility)value;
return v == Visibility.Visible;
}
}

<!-- usage in xaml -->
Visibility="{Binding IsVisible, Converter={converters:BooleanToVisibilityConverterMarkupExtension}}">>