我需要在C#中访问用. xaml创建的TreeView的帮助。我正在创建一个简单的TreeView,它将从文档中收集所有“层”,并使用它们的名称和其他属性填充TreeView。作为起点,我只需要名称,然后添加更多属性。
.xaml如下所示:
<Window x:Class="TestWPFAlpha.DocumentStructureWindow"
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:TestAlpha"
mc:Ignorable="d"
Closing="Window_Closing"
Title=" Document Structure" Height="600" MinHeight="600" MaxHeight="600" Width="400" MinWidth="400" MaxWidth="400" ScrollViewer.VerticalScrollBarVisibility="Visible">
<Grid x:Name="gridDocumentStructure" x:FieldModifier="public">
<Menu Height="25" Margin="0,0,0,0" VerticalAlignment="Top" FontSize="14" Background="#FF3C4B64" Foreground="White">
<MenuItem Header="Search" />
<MenuItem Header="Close" Height="25" Click="buttonCloseDocumentStructureWindow_Click"/>
</Menu>
<TreeView x:Name="TreeViewDocumentStructure" x:FieldModifier= "public" Background="#FFEBEBEB" Margin="10,35,10,10">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Members}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
在C#中,我有:
// all necessary using statements and the two below, that are specific thar I need in this method
using static TestWPFAlpha.DocumentStructureWindow;
using static DocumentLayers.LayerManagerWindow;
...
和按钮事件,如下所示:
public static void DocumentStructure_Click(object sender, RoutedEventArgs e)
{
if (documentStructureWindow == null)
{
documentStructureWindow = new TestWPFAlpha.DocumentStructureWindow();
documentStructureWindow.Show();
}
else
{
documentStructureWindow.Activate();
}
var tds = new TestWPFAlpha.DocumentStructureWindow.gridDocumentStructure.TreeViewDocumentStructure();
System.Type canvasType = typeof(System.Windows.Controls.Canvas);
int count = 0;
foreach (UIElement uie in TestWPFAlpha.MainWindow.canvasGrid.Children)
{
if (uie.GetType() == canvasType && count > 0)
{
sb.AppendLine(Layers[count - 1].Name);
TreeViewItem newChild = new TreeViewItem();
// Layers are from DocumentLayers.LayerManagerWindow
newChild.Header = Layers[count - 1].Name;
tds.Items.Add(newChild);
}
count++;
}
}
在第49行
var tds = new TestWPFAlpha.DocumentStructureWindow.gridDocumentStructure.TreeViewDocumentStructure();
我得到错误:
型别名称'gridDocumentStructure'不存在于型别'DocumentStructureWindow'中
非常感谢您的帮助。
1条答案
按热度按时间qv7cva1a1#
这是你要求的一个例子。这只是一个基本的东西,使用代码
带有树视图的窗口:
它会创建一个新窗口:
newWin
有一个按钮,我想您会希望实现这个功能:请在此处查看:repo
但我建议使用mvvm & commands,而不是这种代码隐藏的解决方案