Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make a ListBox.ItemTemplate reusable/generic
    primarykey
    data
    text
    <p>I'm fairly new to WPF and trying to understand how best to extend the <code>ListBox</code> control. As a learning experience, I wanted to build a <code>ListBox</code> whose <code>ListBoxItem</code>s display a <code>CheckBox</code> instead of just text. I got that working in a basic fashion using the <code>ListBox.ItemTemplate</code>, explicitly setting the names of the properties I wanted to databind to. An example is worth a thousand words, so...</p> <p>I've got a custom object for databinding:</p> <pre><code>public class MyDataItem { public bool Checked { get; set; } public string DisplayName { get; set; } public MyDataItem(bool isChecked, string displayName) { Checked = isChecked; DisplayName = displayName; } } </code></pre> <p>(I build a list of those and set <code>ListBox.ItemsSource</code> to that list.) And my XAML looks like this:</p> <pre><code> &lt;ListBox Name="listBox1"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;CheckBox IsChecked="{Binding Path=Checked}" Content="{Binding Path=DisplayName}" /&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>This works. But I want to make this template reusable, i.e. I'll want to bind to other objects with properties other than "Checked" and "DisplayName". How can I modify my template such that I could make it a resource, reuse it on multiple <code>ListBox</code> instances, and for each instance, bind <code>IsChecked</code> and <code>Content</code> to arbitrary property names?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload