我正在尝试在TreeView
内创建树标题,但不会显示任何内容。在我的程序中,我在画布上创建了一系列具有名称的椭圆对象。我想要做的是:
创建椭圆对象时,使用椭圆名称在TreeView
内创建标题。
由于第一个椭圆的名称为“Circle01”,因此当我释放鼠标左键时,这就是我试图在TreeView
中显示的内容。但是当我这样做时,没有任何反应。
// Ellipse object is created when Left Mouse button is release.
private void _canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (mouseLBDown)
{
mouseLBDown = false;
if (isCreatingEllipse)
{
_debugLabel.Content = "Done.";
isCreatingEllipse = false;
loadToTree = true;
}
}
}
// Suppose to load name of Ellipse as a header, but doesn't.
private void _circleTree_Loaded(object sender, RoutedEventArgs e)
{
if (loadToTree)
{
TreeViewItem item = new TreeViewItem();
item.Header = circle[0].circleName;
_circleTree.Items.Add(item);
loadToTree = false;
}
}
XAML:
<TreeView Name="_boneTree" Background="#404040" Foreground="#E0E0E0"
HorizontalAlignment="Left" Height="422" Margin="970,28,0,0"
VerticalAlignment="Top" Width="212" Loaded="_circleTree_Loaded"/>
答案 0 :(得分:0)
您不应该创建自己的TreeViewItem
,而是设置TreeView
的{{1}}并让WPF为您构建ItemsSource
。在XAML中也更容易做到这一点:
TreeViewItem
Circles是DataContext上的一个属性,默认情况下是你的代码隐藏:
<TreeView Name="_boneTree" Background="#404040" Foreground="#E0E0E0"
HorizontalAlignment="Left" Height="422" Margin="970,28,0,0"
VerticalAlignment="Top" Width="212"
ItemsSource="{Binding Circles}">
<TreeView.Resources>
<Style TargetType="TreeViewItem">
<Setter Property="Header" Value="{Binding circleName}"/>
</Style>
</TreeView.Resources>
</TreeView>
然后,无论何时添加或删除Circle,它都会自动显示在UI上!