<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>FormatException &#187; ListView</title>
	<atom:link href="http://www.formatexception.com/tag/listview/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.formatexception.com</link>
	<description>Ramblings on developing in the Windows World</description>
	<lastBuildDate>Fri, 23 Sep 2011 15:34:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Databinding, ListView/GridView and Converter</title>
		<link>http://www.formatexception.com/2008/10/databinding-listviewgridview-and-converter/</link>
		<comments>http://www.formatexception.com/2008/10/databinding-listviewgridview-and-converter/#comments</comments>
		<pubDate>Tue, 28 Oct 2008 14:56:23 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Databinding]]></category>
		<category><![CDATA[GridView]]></category>
		<category><![CDATA[IValueConverter]]></category>
		<category><![CDATA[ListView]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=106</guid>
		<description><![CDATA[Had some trouble with using a converter when databinding on a GridView yesterday so I thought I&#8217;d do a quick write up. Imagine for one instance you have the following class: public class EntityDataItem { public string Name { get; set; } public string Type { get; set; } public DateTime CreatedTS { get; set; [...]]]></description>
			<content:encoded><![CDATA[<p>Had some trouble with using a converter when databinding on a GridView yesterday so I thought I&#8217;d do a quick write up.</p>
<p>Imagine for one instance you have the following class:</p>
<pre name="code" class="csharp">public class EntityDataItem
{
    public string Name { get; set; }
    public string Type { get; set; }
    public DateTime CreatedTS { get; set; }
}</pre>
<p>Now imagine you have the following xaml:</p>
<pre name="code" class="csharp">&lt;ListView Name="EntitiesGrid"&gt;
&lt;ListView.View&gt;
&lt;GridView&gt;
&lt;GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/&gt;
&lt;GridViewColumn Header="Type" DisplayMemberBinding="{Binding Type}"/&gt;
&lt;GridViewColumn Header="CreatedTS" DisplayMemberBinding="{Binding CreatedTS}"/&gt;
&lt;/GridView&gt;
&lt;/ListView.View&gt;
&lt;/ListView&gt;</pre>
<p>To bind to the grid all you would have to do on the window load event is:</p>
<pre name="code" class="csharp">private void Window_Loaded(object sender, RoutedEventArgs e)
{
    List&lt;EntityDataItem&gt; items = new List&lt;EntityDataItem&gt;();
    items.Add(new EntityDataItem { Name = "A", Type = "Person", CreatedTS = DateTime.Now });
    items.Add(new EntityDataItem { Name = "B", Type = "Equipment", CreatedTS = DateTime.Now });
    items.Add(new EntityDataItem { Name = "C", Type = "Location", CreatedTS = DateTime.Now });
    items.Add(new EntityDataItem { Name = "D", Type = "Unit", CreatedTS = DateTime.Now });
    EntitiesGrid.ItemsSource = items;
}</pre>
<p>Well now, that&#8217;s all fine and good.  But now imagine you were, oh, I don&#8217;t know, working on some military project that wanted you do use a specific format for the date.  The way it is now when the binding happens it will use the default ToString() which isn&#8217;t acceptable in this case.</p>
<p>So we need to use a converter.  Converters let you go from any object to any object on databinding.  Let&#8217;s start by creating the converter:</p>
<pre name="code" class="csharp">[ValueConversion(typeof(DateTime), typeof(String))]
public class DateToMilitaryConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return "";
        DateTime date = (DateTime)value;
        return date.ToString("dd MMM yyyy HHmm", DateTimeFormatInfo.InvariantInfo);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string strValue = value.ToString();
        DateTime resultDateTime;
        if (DateTime.TryParse(strValue, out resultDateTime))
        {
            return resultDateTime;
        }
        return value;
    }
}</pre>
<p>then in the resources for your xaml define:</p>
<pre name="code" class="csharp">&lt;local:DateToMilitaryConverter x:Key="dateConverter"/&gt;</pre>
<p>assuming the local namespace is defined as your local assembly or whatever namespace you used for the converter.</p>
<p>Here&#8217;s where things get a bit tricky.  You can&#8217;t put a converter directly on a GridViewColumn.  Where you can put it is on the Binding.  To do that make your xaml look like:</p>
<pre name="code" class="csharp">&lt;ListView Name="EntitiesGrid"&gt;
    &lt;ListView.View&gt;
        &lt;GridView&gt;
            &lt;GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/&gt;
            &lt;GridViewColumn Header="Type" DisplayMemberBinding="{Binding Type}"/&gt;
            &lt;GridViewColumn Header="CreatedTS"&gt;
                &lt;GridViewColumn.DisplayMemberBinding&gt;
                    &lt;Binding Path="CreatedTS" Converter="{StaticResource dateConverter}"/&gt;
                &lt;/GridViewColumn.DisplayMemberBinding&gt;
            &lt;/GridViewColumn&gt;
        &lt;/GridView&gt;
    &lt;/ListView.View&gt;
&lt;/ListView&gt;</pre>
<p>You can see here we are tapping into the DisplayMemberBinding propery of the GridViewColumn and assigning a Binding to it.  On the Binding we can use a converter.  As I mentioned though you can go from any object to any other object.  Remember, however, regardless of what you go to, the ToString() will be called on it.  A couple of points of interest on the converter.  The source of the data in the real binding, not my contrived example, is a DateTime? which means the value could be null.  Thus I have accounted for that in the converter.  Additionally I allow for a class cast exception rather then doing:</p>
<pre name="code" class="csharp">DateTime date = value as DateTime;
if (value == null)
    return "";</pre>
<p> in case someone else were to use my class where it doesn&#8217;t belong.  Basically the converter handles DateTime? but nothing else, as it should be.</p>
<p>Well, I meant this one to be short and sweet and it was.</p>
<p>Later,<br />
Brian</p>
<p><b>UPDATE:</b><br />
It has been brought to my attention that you can do converters inline with the DisplayMemberBinding.</p>
<pre name="code" class="csharp">&lt;GridViewColumn
    Header="CreatedTS"
    DisplayMemberBinding="{Binding Path=CreatedTS, Converter={StaticResource dateConverter}}"
/&gt;</pre>
<p>Live and learn <img src='http://www.formatexception.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
Brian</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F10%2Fdatabinding-listviewgridview-and-converter%2F&amp;t=Databinding%2C%20ListView%2FGridView%20and%20Converter" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F10%2Fdatabinding-listviewgridview-and-converter%2F&amp;t=Databinding%2C%20ListView%2FGridView%20and%20Converter" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/10/databinding-listviewgridview-and-converter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

