Tôi đang thêm TreeViewItems theo cách thủ công vào mã phía sau và muốn sử dụng DataTemplate để hiển thị chúng nhưng không thể tìm ra cách. Tôi hy vọng sẽ làm một cái gì đó như thế này nhưng các mục được hiển thị dưới dạng tiêu đề trống. Tôi đang làm gì sai?Sử dụng ItemTemplate cho TreeView khi thêm các mục vào mã
XAML
<Window x:Class="TreeTest.WindowTree"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WindowTree" Height="300" Width="300">
<Grid>
<TreeView Name="_treeView">
<TreeView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=Age}" />
</StackPanel>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
Đằng sau đang
using System.Windows;
using System.Windows.Controls;
namespace TreeTest
{
public partial class WindowTree : Window
{
public WindowTree()
{
InitializeComponent();
TreeViewItem itemBob = new TreeViewItem();
itemBob.DataContext = new Person() { Name = "Bob", Age = 34 };
TreeViewItem itemSally = new TreeViewItem();
itemSally.DataContext = new Person() { Name = "Sally", Age = 28 }; ;
TreeViewItem itemJoe = new TreeViewItem();
itemJoe.DataContext = new Person() { Name = "Joe", Age = 15 }; ;
itemSally.Items.Add(itemJoe);
_treeView.Items.Add(itemBob);
_treeView.Items.Add(itemSally);
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}
Cả hai giải pháp của bạn đều hoạt động. Rất tiếc đã mất quá nhiều thời gian để liên hệ lại với bạn. Cuối cùng tôi đã không sử dụng một cây cuối cùng, thay vào đó thực hiện một hộp danh sách phân cấp tùy chỉnh. –
Hoan hô cho Matt! chỉ là những gì tôi cần (giải pháp thứ hai) –