【问题标题】:How create a template XAML style (code behind) WPF如何创建模板 XAML 样式(代码隐藏)WPF
【发布时间】:2018-07-16 18:21:57
【问题描述】:

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

【问题讨论】:

  • 向我们展示您编写的不起作用的代码,我们会告诉您它有什么问题。
  • 我编辑问题
  • 您必须实际阅读错误消息...请将上面的 xaml 与您的 code-xaml-string 进行比较。后者将ListView.ItemsPanel 嵌套在ItemsPanelTemplate 中,这当然是行不通的。
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误以及必要的最短代码在问题本身中重现它。

标签: wpf


【解决方案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 };
}

【讨论】:

  • 如果我可以再问你一件事……为这个组件插入更多属性,例如对齐和大小,会怎样?使用相同的架构 XamlReader,我试图理解...
  • 您应该只将XamlReader 用于无法用 C# 等效编写的内容。大多数 Xaml 代码都可以干净地转换为 C#,但模板是一种特殊情况。要更改任何其他属性,只需直接在实例上更改它,例如 listView.Width = 250listView.HorizontalAlignment = HorizontalAlignment.Center
  • 当然,这很有意义...我现在明白了,再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-21
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
相关资源
最近更新 更多