我对c#wpf有点陌生。我正在尝试制作一个演示应用程序,它使用树视图来显示分层数据。到目前为止,我已经做了以下工作。
- ViewModelBase.cs
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
- 项目.cs
public class Item : ViewModelBase
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public ObservableCollection<Item> Children { get; private set; }
public Item() : this("Item") { }
public Item(string name)
{
Children = new ObservableCollection<Item>();
}
}
- 主窗口.xaml
<Window x:Class="TreeViewDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TreeViewDemo"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TreeView x:Name="TreeView_Items" Grid.Row="0" Grid.Column="0" ItemsSource="{ Binding }">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{ Binding Path=Children }" DataType="{ x:Type local:Item }">
<TextBlock Text="{ Binding Path=Name }" Foreground="Black" Visibility="Visible" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<TreeView x:Name="TreeView_Items1" Grid.Row="0" Grid.Column="1">
<TreeViewItem Header="Item">
<TreeViewItem Header="Item" />
<TreeViewItem Header="Item" />
</TreeViewItem>
<TreeViewItem Header="Item">
<TreeViewItem Header="Item">
<TreeViewItem Header="Item" />
</TreeViewItem>
<TreeViewItem Header="Item" />
</TreeViewItem>
<TreeViewItem Header="Item" />
</TreeView>
<Button x:Name="Button_Add" Grid.Row="1" Grid.Column="0" Content="Add" Click="Button_Add_Click" />
<Button x:Name="Button_Test" Grid.Row="1" Grid.Column="1" Content="Test" />
</Grid>
</Window>
- 主窗口.xaml.cs
public partial class MainWindow : Window
{
public ObservableCollection<Item> Items { get; } = new ObservableCollection<Item>();
public MainWindow()
{
InitializeComponent();
Items.Add(new Item("Parent"));
TreeView_Items.ItemsSource = Items;
}
private void Button_Add_Click(object sender, RoutedEventArgs e)
{
var selected = TreeView_Items.SelectedItem as Item;
if (selected == null)
Items.Add(new Item("Parent"));
else
selected.Children.Add(new Item("Item"));
}
}
问题是,当我编译并运行它时,树视图项不会显示在树视图中,也不会发出任何错误。当我检查实时可视化树时,treeview将textblock作为子项,而不是treeviewitem。实时可视化树图像。如果我点击添加按钮,它只是添加了另一个文本块,而不是树视图项。有人能告诉我我做错了什么吗?
这是因为您没有在Item类中设置名称。正在添加项目,但由于名称为空,您看不到任何内容。
public Item(string name)
{
Name = name;
Children = new ObservableCollection<Item>();
}