'Bind data to defined user control in ListBox - WPF

In WPF, I have a backend data structure -'Dat', and a user control defined for it - 'UC1' - to be view of Dat.

Now I have a backend Dat list. How to make a ListBox contain a corresponding list of UC1? And meanwhile I'm able to retrieve the list of UC1?

Binding between Dat and UC1 is designed like this: a Dat is stored in a UC1, and some Bindings between Dat properties with UC1 properties are set. UC1 has method(including constructor) to set the Dat.

I have tried 2 methods:

  1. Define ItemContainerStyle of the ListBox. Bind ContentControl.Content with a converter who convert Dat to UC1.

with this method, UC1 list is displayed correctly. But I don't know how to retrieve the UC1 list or each UC1 by index - it is tested for non-empty ListBox, ItemContainerGenerator.ContainerFromIndex(0) always returns null.

var ct = new ControlTemplate(typeof(ListBoxItem));
var cc = new FrameworkElementFactory(typeof(ContentControl), "CC");
cc.SetBinding(ContentControl.ContentProperty, new Binding(){Converter = theCvt});
ct.VisualTree = cc;
Setter st = new Setter(ListBox.TemplateProperty, ct);
Style style = new Style();
style.TargetType = typeof(ListBoxItem);
style.Setters.Add(st);
listBox.ItemContainerStyle = style;

listBox.ItemsSource = listOfDat;
  1. use ItemTemplate instead of ItemContainerStyle.

But here I have no idea how to bind UC1 with Dat. my code is weird, and each UC1 appears empty although the converter is called indeed. The 'Dat' below is a DependencyProperty of type Dat in UC1.

<ListBox.ItemTemplate>
  <DataTemplate>
    <local:UC1 Dat="{Binding Converter={StaticResource TheCvt}}/>
  <DataTemplate>
<ListBox.ItemTemplate>

listBox.ItemsSource = listOfDat;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source