如何创建模板XAML样式(代码隐藏)WPF

时间:2018-02-06 16:08:58

标签: wpf

我在我的xaml上有这个代码并且运行正常(ListView组件)

<ListView.ItemsPanel>
  <ItemsPanelTemplate>
    <StackPanel Orientation="Horizontal"></StackPanel>
  </ItemsPanelTemplate>

我正在尝试使用这个答案Create DataTemplate in code behind复制代码,但我无法使其工作(Russell的回答)。任何帮助将不胜感激。谢谢!

编辑:

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;
}

1 个答案:

答案 0 :(得分:1)

如果您删除ListView.ItemsPanel元素和内部ItemsPanelTemplate元素,您的代码就会有用:

private ItemsPanelTemplate GetItemsPanelTemplate()
{
    return XamlReader.Parse(
        @"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
            <StackPanel Orientation='Horizontal' IsItemsHost='True' />
          </ItemsPanelTemplate>") as ItemsPanelTemplate;
}

但是,根据您链接的答案,首选方式是:

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 };
}