WPF DateTime Formatting -
i need format date, used below:
<xcdg:column title="registratiedatum" fieldname="registratiedatum" width="1*"> <xcdg:column.cellcontenttemplate> <datatemplate> <textblock text="{binding stringformat='{}{0:dd/mm/yyyy hh:mm:ss }', targetnullvalue={x:static system:string.empty}}" /> </datatemplate> </xcdg:column.cellcontenttemplate> </xcdg:column>
however, of date null, fields remain empty, guess due formatting appears this:
01/01/0001 00:00:00
any idea how restrict format "not null" values? sorry, if might basic question, still @ beginning stage of learning.
a struct
being value type
, can never null
.
however, there several ways can fix issue:
the cleanest , logical, in opinion, change datetime
nullable<datetime>
private datetime? mydate; public datetime? mydate { { return this.mydate; } set { this.mydate = value; } }
if not option, converter trick:
.xaml code:
<usercontrol.resources> <local:dateconverter x:key="dateconverter"/> </usercontrol.resources> <textblock text="{binding mydate, converter={staticresource dateconverter}}" />
.cs code
public class dateconverter: ivalueconverter { public object convert(object value, type targettype, object parameter, cultureinfo culture) { if (value != null) { datetime mydate = (datetime)value; if (mydate != datetime.minvalue) { return mydate.tostring("dd/mm/yyyy hh:mm:ss"); } } return string.empty; } public object convertback(object value, type targettype, object parameter, cultureinfo culture) { throw new notimplementedexception(); } }
finally, datatrigger directly in xaml code allows hide/collapse control when date null. key, in converter check when date equal
datetime.minvalue
.<usercontrol x:class="wpfapplicationtest.myusercontrol" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:sys="clr-namespace:system;assembly=mscorlib" xmlns:local="clr-namespace:wpfapplicationtest" mc:ignorable="d" d:designheight="300" d:designwidth="300"> <textblock text="{binding mydate, stringformat='{}{0:dd/mm/yyyy hh:mm:ss }'}" > <textblock.style> <style targettype="textblock"> <style.triggers> <datatrigger binding="{binding mydate}" value="{x:static sys:datetime.minvalue}"> <setter property="visibility" value="collapsed"></setter> </datatrigger> </style.triggers> </style> </textblock.style> </textblock>
Comments
Post a Comment