c# - 如何在代码隐藏中更改 ItemsPanelTemplate?

标签 c# .net xaml uwp

<ItemsControl>        
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

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

我读了这个here但想不通。

最佳答案

我更喜欢在 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# - 如何在代码隐藏中更改 ItemsPanelTemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44555462/

相关文章:

c# - 如何解析 Autofac 中的依赖项列表?

c# - Encoding.Default 在 .NET 中如何工作?

c# - 正确打印二维数组?

c# - DropShadowPanel 和边框圆角半径

WPF ScrollViewer : tap=click, 点击并按住/拖动=滚动。如何做到这一点?

c# - dll引用最佳实践

c# - WebBrowser HtmlElement.GetAttribute ("href") 前置主机名

c# - 在来自asp.net的上传文件中以C#编辑mp3

c# - 访问 HTTPS Web 服务器时抛出 HttpWebRequest System.Net.WebException

c# - Wpf如何根据变量动态渲染按钮