Reputation: 19
I´m working on a WPF project with a Treeview - and the following Model objects
PersonModel
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string FullName
{
get { return FirstName + " " + LastName; }
}
EmployeeModel : PersonModel
public int MonthlySalary { get; set; }
public int MonthlyHours { get; set; }
MainWindowViewModel
public ObservableCollection<EmployeeModel> Employees
{
get { return _employees; }
set { _employees = value; }
}
MainWindow XAML
<TreeView ItemsSource="{Binding Employees}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Employees}">
<TreeViewItem Header="{Binding FullName}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
So fare I´m getting a list of epmloyees (the fullname) and what I would like to do is to have MonthlySalary and MonthlyHours as children like:
- John Doe
- 30 hours
- 5.000 dollars
- Jane Doe
- 40 hours
- 10.000 dollars
Any suggestions to how I should setup the XAML in order to list data the way I want to? Regards
Upvotes: 1
Views: 505
Reputation: 2509
Here's some XAML for you:
<Window x:Class="WpfApp4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp4"
Title="MainWindow"
Width="800"
Height="450"
UseLayoutRounding="True">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="HoursTemplate" DataType="{x:Type local:EmployeeModel}">
<TextBlock>
<Run Text="{Binding MonthlyHours}" />
<Run Text=" hours" />
</TextBlock>
</DataTemplate>
<DataTemplate x:Key="SalaryTemplate" DataType="{x:Type local:EmployeeModel}">
<TextBlock>
<Run Text="{Binding MonthlySalary}" />
<Run Text=" dollars" />
</TextBlock>
</DataTemplate>
</Window.Resources>
<Grid>
<TreeView ItemsSource="{Binding Employees}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Employees}">
<TreeViewItem
Header="{Binding FullName}"
IsExpanded="True">
<TreeViewItem
Header="{Binding}"
HeaderTemplate="{StaticResource HoursTemplate}" />
<TreeViewItem
Header="{Binding}"
HeaderTemplate="{StaticResource SalaryTemplate}" />
</TreeViewItem>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
I hope this helps.
Upvotes: 1