我需要在代码隐藏中为 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)在设计时不存在。您正在运行时创建并添加它。
因此,如果您引用此数据模板,则
将资源添加到资源字典后引用该资源。
例如
myWindow.Resources.Add( "MasterDetailTemplate", dataTemplate); myTreeView.ItemTemplate = myWindow.Resources["MasterDetailTemplate"] as HierarchicalDataTemplate;
在 XAML 中将动态创建的数据模板引用为
DynamicResource
。DynamicResource
消除了在任何资源字典中预先存在MasterDetailTemplate
的需要。<TreeView ItemTemplate="{DynamicResource MasterDetailTemplate}" ... > .... </TreeView>
希望这有帮助。
关于c# - 如何在代码隐藏中创建 HierarchicalDataTemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7833981/