title: How to apply a style to a ListBox in code
body: <p>I have a case where some people are divided into several groups with the people and groups coming from a database.  I want to display this data as a series of ListBoxes for each group with the people in that group displayed in the ListBox.  I do this in code for each group as follows:</p>
  
  <ol>
  <li><p>First I define a ListBox</p>
  
  <pre><code>lbx = New ListBox
  With lbx
     .ContextMenu = cm
     .DisplayMemberPath = "FullName"
     .SelectedValuePath = "PersonID"
  End With
  </code></pre></li>
  <li><p>Then I populate an ObservableCollection (of Person) from the database then assign that collection as the ItemsSource of the ListBox.</p>
  
  <pre><code>lbx.ItemsSource = ocGrouMembers
  </code></pre></li>
  <li><p>Then I add the ListBox to a panel named "pnl" that I've defined in XAML.</p>
  
  <pre><code>pnl.Children.Add(lbx)
  </code></pre></li>
  </ol>
  
  <p>Now comes the problem: I want to change the presentation of some of the people in the ListBoxes.  First, I thought I'd define a Style in XAML with TargetType = ListBoxItem.  But this won't work because nowhere in code do I ever explicitly define the ListBoxItems so there is no way to define a style for them.</p>
  
  <p>Second, I thought of creating a DataTemplate in XAML but as far as I can tell there is no way in code to apply a DataTemple directly to the ListBoxes.</p>
  
  <p>I hope this is clear.  How can I change the appearance of the names in theListBoxes in this case?</p>
  
  <p><strong>EDIT: Final Solution</strong></p>
  
  <p>I ended up defining data template in XAML as follows:</p>
  
  <pre><code>&lt;DataTemplate
      DataType="ListBoxItem"
      x:Key="dtpListBoxItem"&gt;
      &lt;TextBlock
          x:Name="txtPerson"
          Text="{Binding FullName}"&gt;
      &lt;/TextBlock&gt;
      &lt;DataTemplate.Triggers&gt;
          &lt;DataTrigger
              Binding="{Binding Path=Chair}" Value="True"&gt;
              &lt;Setter TargetName="txtPerson"  Property="Foreground" Value="Blue" /&gt;
              &lt;Setter TargetName="txtPerson" Property="FontWeight" Value="DemiBold" /&gt;
          &lt;/DataTrigger&gt;
      &lt;/DataTemplate.Triggers&gt;
  &lt;/DataTemplate&gt;
  </code></pre>
  
  <p>And in code used it as follows:</p>
  
  <pre><code>lbx = New ListBox
      With lbx
          ... other properties ....
          .ItemTemplate = DirectCast(Resources("dtpListBoxItem"), DataTemplate)
      End With
  </code></pre>