【问题标题】:How Can I Change an ItemsPanelTemplate in Code Behind?如何在代码后面更改 ItemsPanelTemplate?
【发布时间】:2017-11-17 05:41:04
【问题描述】:
<ItemsControl>        
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

如果我想将 ItemsPanelTemplate 从默认 (StackPanel) 更改为网格,我在 XAML 中执行上述操作。我怎样才能在代码中实现同样的功能?

我读到了这个here,但不明白。

【问题讨论】:

  • 不要粗鲁;只是你所问的并不是 WPF 的真正预期工作方式。
  • 嗯,它不是 WPF,它是 UWP。我在 C# 中创建了一个自定义控件,它继承了 ItemsControl 并根据算法将每个子元素放置在放射状图案中。模板必须始终是 Grid,不能是 StackPanel。
  • 不管怎样;这种隐藏代码的恶作剧通常不是理想的方式。如果您正在创建自定义控件,您不能将您的 XAML 放入控件模板中并称其为好?
  • 我在 NuGet 上看到的每个自定义控件都包含一个 C# 文件。
  • 如果您总是想要一个 Grid 作为 ItemsPanel,您可以在 Generic.xaml 中自定义控件的默认样式中定义它。

标签: c# .net xaml uwp


【解决方案1】:

我更喜欢在 Generic.xaml 中以自定义控件的默认样式执行此操作,但如果您想要纯 C# 方式,可以这样做 -

private void ApplyGridAsItemsPanel()
{
    MyItemsControl.ItemsPanel = ParseItemsPanelTemplate(typeof(Grid));

    ItemsPanelTemplate ParseItemsPanelTemplate(Type panelType)
    {
        var itemsPanelTemplateXaml =
            $@"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                                  xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                   <{panelType.Name} />
               </ItemsPanelTemplate>";

        return (ItemsPanelTemplate)XamlReader.Load(itemsPanelTemplateXaml);
    }
}

【讨论】:

  • 谢谢。我知道这是非常规的,我很有可能会接受这个建议。我没有意识到这会涉及 c# 文件中的实际 xaml 语法,我同意这很荒谬。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
  • 2013-12-14
  • 1970-01-01
  • 2016-06-05
相关资源
最近更新 更多