您需要为 SubGroups 定义第二个类,因此您可以为 Groups 定义一个 DataTemplate,为 SubGroups 定义一个。您的模型类可能类似于
public class Group {
public string Name { get; set; }
public List<SubGroup> SubGroups { get; set; }
public Group(string name) { this.Name = name; }
}
public class SubGroup {
public string Name { get; set; }
public SubGroup(string name) { this.Name = name; }
}
在 WPF 中,您可以为每种类型定义一个 DataTemplate:
<Window.Resources>
<DataTemplate DataType="{x:Type local:SubGroup}">
<StackPanel Orientation="Horizontal">
<TextBlock Text=" +-- "/><TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Group}">
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<ItemsControl ItemsSource="{Binding SubGroups}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding}" />
</Grid>
编辑(在查看 Bhattis 编辑后):
如果子组项目也应该是可点击的,那么(恕我直言)从 ListBox 的角度来看,组和子组之间没有区别。所以我的解决方法猜测是:
public class Groups {
public string Group { get; set; }
}
在 WPF 窗口中
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Path=Group}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
并且在 WPF 代码隐藏文件中:
public MainWindow() {
InitializeComponent();
Groups g1 = new Groups() { Group = "Parent 1" };
Groups s1 = new Groups() { Group = " Sub 1" };
Groups s2 = new Groups() { Group = " Sub 2" };
Groups g2 = new Groups() { Group = "Parent 2" };
Groups s3 = new Groups() { Group = " Sub 1" };
Groups s4 = new Groups() { Group = " Sub 2" };
this.DataContext = new List<Groups>() { g1, s1, s2, g2, s3, s4 };
}
这里的每个子组都只是一个组,因此每条“行”都是可点击的。重要的是列表的顺序很重要,因为结构不再在模型中。
如果您必须根据用户单击组还是子组做出不同的反应,那么您可以在模型中构建继承层次结构并将相应的对象放入 DataContext 中。为了把你引向正确的方向,我的意思是像
public abstract class AbstractGroup {
public string Name { get; set; }
public AbstractGroup(string name) { this.Name = name; }
}
public class Group : AbstractGroup {
public Group(string name) : base(name) {}
}
public class SubGroup : AbstractGroup {
public SubGroup(string name) : base(name) {}
}
代码隐藏:
InitializeComponent();
AbstractGroup g1 = new Group("Parent 1");
AbstractGroup s1 = new SubGroup(" Sub 1");
AbstractGroup s2 = new SubGroup(" Sub 2");
AbstractGroup g2 = new Group("Parent 2");
AbstractGroup s3 = new SubGroup(" Sub 1");
AbstractGroup s4 = new SubGroup(" Sub 2");
this.DataContext = new List<AbstractGroup>() { g1, s1, s2, g2, s3, s4 };
XAML:
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
由于您可以在 DataContext 中获取所选对象,因此 typeof() 可以帮助您找出所选项目的具体类型。