gpt4 book ai didi

c# - 当不将子节点添加到vm的构造函数中时,WPF TreeView 不显示子节点

转载 作者:行者123 更新时间:2023-12-03 10:37:22 25 4
gpt4 key购买 nike

WPF树 View 有一个奇怪的问题。在我的 View 模型中,我正在这样做:

private ObservableCollection<ITreeItem> _Tree = new ObservableCollection<ITreeItem>();
public ObservableCollection<ITreeItem> Tree
{
get { return this._Tree; }
}

现在,当我在viewmodel的构造函数中添加一些虚拟的Parent/child数据时,如下所示:
var parent = new ParentItem(1, "test", "test2");
this.Tree.Add(parent);
for (int i = 0; i < 10; i++)
{
parent.Childs.Add(new Child { Name= "test", Description= "test2" });
}
parent.IsExpanded = true;

树显示正确。

但是,一旦我通过方法(使用调度程序)添加了一些子项,它们根本就不会显示。例如,当我调用此方法时,仅显示根节点。
public void Update()
{
DispatcherSingleton.Instance.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(delegate
{
var parent = new ParentItem(1, "test", "test2");
this.Tree.Add(parent);
for (int i = 0; i < 10; i++)
{
parent.Childs.Add(new Child { Name= "test", Description= "test2" });
}
parent.IsExpanded = true;
})
);
}

这是树 View 的XAML
<ResourceDictionary>
<Style TargetType="TreeViewItem" x:Key="itmContStyle">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
</Style>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
<HierarchicalDataTemplate x:Key="hDataTemplate" ItemsSource="{Binding Childs}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Image, Mode=TwoWay}" Margin="1" />
<Image x:Name="currentImage" Source="/WpfApp;component/Resources/Images/ac.png" Visibility="Collapsed"></Image>
<TextBlock Text="{Binding SortOrder}" Margin="1" />
<TextBlock Text="." Margin="0,1,1,0" />
<TextBlock Text="{Binding Bezeichnung}" Margin="1" />
</StackPanel>
<HierarchicalDataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=TreeViewItem}, Path=IsSelected}" Value="True">
<Setter TargetName="currentImage" Property="Visibility" Value="Visible"/>
</DataTrigger>
</HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>
</ResourceDictionary>

...

<TreeView HorizontalAlignment="Stretch" VerticalAlignment="Top"
BorderThickness="0"
ItemsSource="{Binding Tree}"
ItemContainerStyle="{StaticResource itmContStyle}" ItemTemplate="{StaticResource hDataTemplate}">
</TreeView>

最佳答案

您似乎混淆了命名。在您的代码中,显示以下行:

parent.Childs.Add(new Child { Name= "test", Description= "test2" });

这使我认为您的数据类型具有 Childs属性。但是,在您的XAML中,您有以下内容:
<HierarchicalDataTemplate x:Key="hDataTemplate"  ItemsSource="{Binding ChildSteps}">
...
</HierarchicalDataTemplate>

我猜其中之一是错误的。因此,请尝试以下XAML:
<HierarchicalDataTemplate x:Key="hDataTemplate"  ItemsSource="{Binding Childs}">
...
</HierarchicalDataTemplate>

关于c# - 当不将子节点添加到vm的构造函数中时,WPF TreeView 不显示子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20564259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com