c# - 如何在代码隐藏中创建 HierarchicalDataTemplate?

标签 c# .net wpf datatemplate hierarchicaldatatemplate

我需要在代码隐藏中为 TreeView 创建一个 HierarchicalDataTemplate

这就是我的 XAML 的样子:

<DataTemplate x:Key="DetailTemplate">
        <StackPanel Orientation="Horizontal">
            <Image Height="15" Width="15" Source="{Binding Image}" Margin="0,0,5,0"/>
            <TextBlock Text="{Binding Text}" />
        </StackPanel>
    </DataTemplate>

    <HierarchicalDataTemplate x:Key="MasterDetailTemplate" 
                              ItemsSource="{Binding SomeSource}" 
                              ItemTemplate="{StaticResource DetailTemplate}">
        <StackPanel Orientation="Horizontal">
            <Image Height="15" Width="15" Source="{Binding Image}" Margin="0,0,5,0"/>
            <TextBlock Text="{Binding Text}" />
        </StackPanel>
    </HierarchicalDataTemplate>

这是我迄今为止在 C# 中得到的:

        Image image = new Image();
        image.Name = "image";
        image.Height = 15;
        image.Width = 15;

        Binding imageBinding = new Binding("Image");
        BindingOperations.SetBinding(image, Image.SourceProperty, imageBinding);

        TextBlock textBlock = new TextBlock();
        textBlock.Name = "textBlock";

        Binding textBinding = new Binding("Text");
        BindingOperations.SetBinding(textBlock, TextBlock.TextProperty, textBinding);

        StackPanel stackPanel = new StackPanel();
        stackPanel.Orientation = Orientation.Horizontal;

        stackPanel.Children.Add(image);
        stackPanel.Children.Add(textBlock);

        DataTemplate dataTemplate = new DataTemplate();
        dataTemplate.DataTemplateKey

我被困在 DataTemplateKey 处。

  • 这可以在代码隐藏中完成吗?
  • 从这里到哪里设置 x:Key 值?

最佳答案

好的,在我对您的问题的评论中,我指定了指定模板方式背后的代码。现在,当我们将它们添加到 ResourceDictionaties 中时,要使用/通过键引用它们,我们必须使用键添加它们。

   myWindow.Resources.Add("MasterDetailTemplate", dataTemplate);

它可以是myParentPanel,而不是myWindow,即 TreeView 的任何祖先。

但是有一个问题..

key (即 DataTemplate)在设计时不存在。您正在运行时创建并添加它。

因此,如果您引用此数据模板,则

  1. 将资源添加到资源字典后引用该资源。

    例如

    myWindow.Resources.Add(
         "MasterDetailTemplate",
         dataTemplate);
    
     myTreeView.ItemTemplate
       = myWindow.Resources["MasterDetailTemplate"] as HierarchicalDataTemplate;
    
  2. 在 XAML 中将动态创建的数据模板引用为 DynamicResourceDynamicResource 消除了在任何资源字典中预先存在 MasterDetailTemplate 的需要。

    <TreeView ItemTemplate="{DynamicResource MasterDetailTemplate}" ... >
      ....
    </TreeView>
    

希望这有帮助。

关于c# - 如何在代码隐藏中创建 HierarchicalDataTemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7833981/

相关文章:

c# - 托盘图标看起来不错,但 WPF 窗口图标看起来很糟糕

wpf - 包含逗号作为绑定(bind)路径的字典字符串键

c# - 如何在c#中将图像从本地系统上传到azure blob存储

c# - 使 Asp.net-Identity 中的 OAuth token 无效

c# - 我如何获得一个月的最后一天?

c# - 性能计数器平均计时器如何与其基数相关联?

WPF DataGrid 控件模板

c# - 如何使用 c# winform 将 10,000 行数据从存储过程移动到 excel

c# - List<SelectListItem> 如何在 View 中安全地转换为 SelectList

.net - 如何使用响应式框架将两个异步操作链接在一起?