C# 将TreeView(再次,是的)绑定到我的类列表
所以,用几句话来说。我有一个类的结构,每个类都包含另一个类的“子”项。我需要为每个类使用自定义模板将其绑定到TreeView 主类如下所示,再加上一些属性和方法:C# 将TreeView(再次,是的)绑定到我的类列表,c#,wpf,xaml,treeview,C#,Wpf,Xaml,Treeview,所以,用几句话来说。我有一个类的结构,每个类都包含另一个类的“子”项。我需要为每个类使用自定义模板将其绑定到TreeView 主类如下所示,再加上一些属性和方法: public static class TreeVM { public string Name { get; set; } public static List<ConfigVM> configsVM = new List<ConfigVM>(); } 类ComPortVM等也是如
public static class TreeVM
{
public string Name { get; set; }
public static List<ConfigVM> configsVM = new List<ConfigVM>();
}
类ComPortVM
等也是如此
我需要用TreeView显示它。我编写了一些xaml代码来定义每个类的视图:
<HierarchicalDataTemplate DataType="{x:Type vm:TreeVM}" ItemsSource="{Binding configsVM}">
<StackPanel Orientation="Horizontal">
<RadioButton Height="16" GroupName="Config" VerticalAlignment="Center" HorizontalAlignment="Left"/>
<Image Source="Icons/IconConfig.png"/>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type vm:ConfigVM}" ItemsSource="{Binding _comPortsVM}">
<StackPanel Orientation="Horizontal">
<CheckBox Height="16" VerticalAlignment="Center" HorizontalAlignment="Left"/>
<Image Source="Icons/IconComPort.png"/>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
和TreeView:
<Grid x:Name="GridForTreeView" DataContext="{Binding vm:TreeVM}">
<TreeView x:Name="ComPortsTree"
ItemsSource="{Binding}" />
</Grid>
但它不起作用
如何使其正确?尝试替换
public static List<ConfigVM> configsVM = new List<ConfigVM>();
public static List configsVM=new List();
为了
public List configsVM{get;set}
然后在构造函数中初始化列表
public TreeVM (){ configsVM = new List<ConfigVM> ();}
public TreeVM(){configsVM=new List();}
对另一个班也这样做
然后在XAML中尝试执行以下操作:
<Grid x:Name="GridForTreeView" DataContext="{Binding vm:TreeVM}">
<TreeView x:Name="ComPortsTree"
ItemsSource="{Binding configsVM }" ItemTemplate= {StaticResource hierachTemplate} />
</Grid>
在您的层次结构中:
<HierarchicalDataTemplate x:Name="hierachTemplate" ItemsSource="{Binding comPortsVM }">
我想就是这样了……试试看吧哦,我为这么长时间的反应道歉:我把我的C#和xaml研究放在一边一段时间,忘记了这个问题。不过,你的回答现在对我帮助很大,谢谢!
<Grid x:Name="GridForTreeView" DataContext="{Binding vm:TreeVM}">
<TreeView x:Name="ComPortsTree"
ItemsSource="{Binding configsVM }" ItemTemplate= {StaticResource hierachTemplate} />
</Grid>
<HierarchicalDataTemplate x:Name="hierachTemplate" ItemsSource="{Binding comPortsVM }">