title: Create ItemTemplate for ListBox in code-behind in WPF - Part II
body: <p>I named this question of mine Part II since I've already asked a similar but simpler question about creating an ItemTemplat for ListBox in WPF in here <a href="https://stackoverflow.com/questions/23079496/create-itemtemplate-for-listbox-in-code-beind-in-wpf">Create ItemTemplate for ListBox in code-beind in WPF</a></p>
  
  <p>Now I'm going to expand my question. I want to have an ItemTemplate for a ListBox so that it can be used either with or without binding to an ObservableCollection.</p>
  
  <p>If I don't want to bind the ItemsSource to an ObservableCollection I use the code as follows:</p>
  
  <pre><code>var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
  textBlockFactory.SetValue(TextBlock.TextProperty, new Binding(".")); // Here
  textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.Red);
  textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Wheat);
  textBlockFactory.SetValue(TextBlock.FontSizeProperty, 18.0);
  
  var template = new DataTemplate();            
  template.VisualTree = textBlockFactory;
  
  MyListBox.ItemTemplate = template;
  </code></pre>
  
  <p>But it doesn't work for ItemsSource binding to an ObservableCollection since the TextBlock.TextProperty must binds to the DisplayMemberPath property.</p>
  
  <p>Sorry for bad grammar.</p>