MikeHouston.net

Honorary member of the Shaolin

Binding in XAML sux!

It appears there is no ‘real’ implementation for formatting or any ‘expressions’ in the binding syntax for XAML.  What a POS!

In order to format dates when binding in XAML I had to…

Create a implementation of IValueConverter  :

    public class ShortDateFormatConverter : IValueConverter

    {

        /*point of interest here – targetType appears to always be string; no matter what the actual type bound to is---WTF?*/

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

        {

            DateTime dateToFormat;           

            if (DateTime.TryParse(value.ToString(), out dateToFormat))

            {

                /*this is just so I could pass in any of the ‘format’ methods*/

                return dateToFormat.GetType().InvokeMember(parameter.ToString(), System.Reflection.BindingFlags.InvokeMethod, null, dateToFormat,null).ToString();

            }

            else

            {

                return string.Empty;

            }

        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

        {

            throw new NotSupportedException("Cannot convert back at this time - if you need this access the object's individual properties");

        }

    }

 

Import the namespace :

<Window x:Class="test.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:cvrt="clr-namespace:test"

    Title="testing" Height="300" Width="709">

 

Set up the Converter to be used in the markup (create window resource) :

  <Window.Resources>

    <cvrt:StringConverter x:Key="StringConverter" />

    <cvrt:ShortDateFormatConverter x:Key="ShortDateFormatConverter" />

  </Window.Resources

 

At this point, I’m finally finished putting all the crap in place to actually bind a property to a ui object and use the converter to format it :

    <TextBox Text="{Binding Path=DtTest, Converter={StaticResource ShortDateFormatConverter}, ConverterParameter=ToLongDateString}" />

<!—any of the ‘format’ methods on DateTime will work here, like ToShortDateString, etc. à

 

If there really isn’t a ‘built-in’ way to apply basic expressions when binding in the markup then DataBinding in XAML is completely useless…and a half-ass implementation at best! 

That’s my last rant on that for the day ;-P

Technorati Tags: , , ,
Comments are closed