I’ve got some Xaml (WPF) that I’m trying to re-create in code. I think I’m close but I’m having a bit of trouble… here’s my Xaml:
<ListView Name="lbDevices" SelectionChanged="lbDevices_SelectionChanged" VerticalAlignment="Stretch" Grid.Row="1">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" Width="{Binding (FrameworkElement.ActualWidth), RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}" ScrollViewer.HorizontalScrollBarVisibility="Hidden"></WrapPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.View>
<GridView>
<GridView.ColumnHeaderContainerStyle>
<Style>
<Setter Property="FrameworkElement.Visibility" Value="Collapsed" />
</Style>
</GridView.ColumnHeaderContainerStyle>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<!-- This is a custom control -->
<l:HaDeviceDisplayer DataContext="{Binding .}" ></l:HaDeviceDisplayer>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
The above gives me a perfect display of what I need. It looks like this:
Here’s my attempt at re-creating it in code:
GridView gv = new GridView();
gv.AllowsColumnReorder = false;
var hiddenStyle = new Style();
gv.ColumnHeaderContainerStyle = hiddenStyle;
gv.ColumnHeaderContainerStyle.Setters.Add(new Setter(FrameworkElement.VisibilityProperty, Visibility.Collapsed));
ItemsPanelTemplate panelTemplate = new ItemsPanelTemplate();
var fact = new FrameworkElementFactory(typeof(WrapPanel));
fact.SetValue(WrapPanel.OrientationProperty, Orientation.Horizontal);
fact.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Hidden);
var binding = new Binding() {
RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ScrollContentPresenter), 1),
Path = new PropertyPath("(FrameworkElement.ActualWidth)")
};
fact.SetBinding(WrapPanel.WidthProperty, binding);
panelTemplate.VisualTree = fact;
lbDevices.ItemsPanel = panelTemplate;
GridViewColumn c1 = new GridViewColumn();
c1.CellTemplate = (DataTemplate)FindResource("DeviceDisplayer");
lbDevices.View = gv;
A couple of notes. Instead of trying to re-create the DataTemplate exactly as I had it in Xaml, I stuck it in a UserControl.Resources tag in the Xaml. I then use the FindResource to set the CellTemplate.
So here’s my problem. When I do the above, the layout ends up looking like this:

Notice the very small orange dot… there’s about a dozen of them that are visible only because selecting an item highlights it with an orange border. For same reason each list item is small. The trouble is – how do I make it “normal” sized?
I never did figure out why my code didn’t match the XAML. Instead, I ended up using XAML and then just creating a reference to the View to re-use for later.