我尝试在wpf的树视图中显示分层数据。 db表是一个自我 引用员工表。
当我绑定到Xaml中的Observable集合时,没有任何东西出现。
以下是示例视图模型
public class EmployeeViewModel : ViewModel
{
public class EmployeeList
{
public Employee Employees { get; set; }
public IEnumerable<EmployeeList> EmployeeChildren { get; set; }
}
private readonly ObservableCollection<EmployeeList> _EmployeeLists = new ObservableCollection<EmployeeList>();
//property
public ObservableCollection<EmployeeList> EmployeeHierarchy
{
get
{
return _EmployeeLists;
}
}
//This is inside a method to make the db call
try
{ //Grab Employees from db using Wcf and EF
WcfProxy.Using(delegate(IMyService client)
{
_EmployeeLists.Clear();
var query = client.GetEmployees();
var results = GetEmployeesHierachy(query.AsEnumerable(), null).ToList();
});
}
catch (Exception e)
{
throw e;
}
}
//Method to build hierarchy
public IEnumerable<EmployeeList> GetEmployeesHierachy(IEnumerable<Employee> allEmployees, Employee parentEmployee)
{
int? parentEmployeeId = null;
if (parentEmployee != null)
parentEmployeeId = parentEmployee.EmployeeId;
var childEmployees = allEmployees.Where(e => e.EmployeeParentId == parentEmployeeId);
foreach (var emp in childEmployees)
_EmployeeLists.Add(new EmployeeList() { Employees = emp, EmployeeChildren = GetEmployeesHierachy(allEmployees, emp) });
return _EmployeeLists;
}
}
这是xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="325" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TreeView Name="ItemTreeView"
ItemsSource="{Binding Path=EmployeeHierarchy}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Employees}">
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" FontFamily="Segoe UI" FontSize="14"
Text="{Binding Path=Name1, StringFormat='Employee Full Name {0}'}" Padding="2"
Width="200" />
<TextBlock Grid.Column="1" FontFamily="Segoe UI" FontSize="14" Padding="2" />
</Grid>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
EF将Name1作为字符串从Employee实体返回,这是我的textblock所绑定的。
我使用的Employee实体中的3个属性是EmployeeId,EmployeeParentId和Name
我错过了xaml中的内容吗?