Reputation: 23
I have this code on my xaml and works fine (ListView component)
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
I´m trying to replicate on code behind using this answer Create DataTemplate in code behind, but i could not make it work (the Russell´s answer). Any help will be appreciated. Thanks!
Edit:
ListView listView = new ListView();
listView.ItemsPanel = GetItemsPanelTemplate();
private ItemsPanelTemplate GetItemsPanelTemplate()
{
string xaml = @"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation=""Horizontal""></StackPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ItemsPanelTemplate>";
return XamlReader.Parse(xaml) as ItemsPanelTemplate;
}
Upvotes: 0
Views: 190
Reputation: 25623
Your code would work if you stripped out the ListView.ItemsPanel
element and the inner ItemsPanelTemplate
element:
private ItemsPanelTemplate GetItemsPanelTemplate()
{
return XamlReader.Parse(
@"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
<StackPanel Orientation='Horizontal' IsItemsHost='True' />
</ItemsPanelTemplate>") as ItemsPanelTemplate;
}
However, the preferred way, based on the answer you linked, would be:
private ItemsPanelTemplate GetItemsPanelTemplate()
{
var factory = new FrameworkElementFactory(typeof(StackPanel));
factory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
factory.SetValue(Panel.IsItemsHostProperty, true);
return new ItemsPanelTemplate { VisualTree = factory };
}
Upvotes: 1