title: Variable Date Format for WPF DataGrid in C#
body: <p>I have a <code>DateTime</code> field in a <code>List&lt;&gt;</code> used as <code>ItemSource</code> in a WPF <code>DataGrid</code> that I would like to format differently depending on the value.  </p>
  
  <p>If the <code>DateTime</code> value is within a year of <code>DateTime.Now</code>, I want to use <code>'MMM dd hh:mm'</code> as formatting, if it is beyond a year of <code>DateTime.Now</code>, I want to use <code>'MMM dd yyyy'</code> as formatting, and if is exactly <code>DateTime.MinValue</code>, then a wish that the cell in the data grid is blank.</p>
  
  <p>This is the code that I have that currenly only shows dates with <code>'MMM dd hh:mm'</code> as format.</p>
  
  <p>Is it possible to define this variable formatting directly in the XAML? </p>
  
  <p>If not, how can I patch the formatting programatically in the DataGrid_Loaded event?</p>
  
  <p><img src="https://i.stack.imgur.com/Kw1Hv.png" alt="Screenshot of the code&#39;s output"></p>
  
  <pre><code>   public class DeadlineItem
      {
          public string Name { get; set; }
          public DateTime Deadline {get; set; }
  
          public DeadlineItem(string aName, DateTime aDeadline)
          {
              this.Name = aName;
              this.Deadline = aDeadline;
          }
      }
  
      private void DataGrid_Loaded(object sender, RoutedEventArgs e)
      {
          var items = new List&lt;DeadlineItem&gt;();
  
          items = new List&lt;DeadlineItem&gt;();
          items.Add(new DeadlineItem("Distant deadline", DateTime.Now.AddDays(500)));
          items.Add(new DeadlineItem("Near Deadline", DateTime.Now.AddDays(1)));
          items.Add(new DeadlineItem("No Deadline", DateTime.MinValue));
          // ... Assign ItemsSource of DataGrid.
          var grid = sender as DataGrid;
          grid.ItemsSource = items;
      }
  </code></pre>
  
  <p>And the XAML is:</p>
  
  <pre><code>&lt;DataGrid
          AutoGenerateColumns="False"
          HorizontalAlignment="Left"
          Margin="0,0,0,0"
          VerticalAlignment="Top"
          Loaded="DataGrid_Loaded"&gt;
                  &lt;DataGrid.Columns&gt;
                      &lt;DataGridTextColumn Header="Name" Binding="{Binding Name}" /&gt;
                      &lt;DataGridTextColumn Header="Deadline" Binding="{Binding Deadline, StringFormat=\{0:MMM dd HH:mm\}}" /&gt;
                  &lt;/DataGrid.Columns&gt;
              &lt;/DataGrid&gt;
  </code></pre>