【发布时间】:2020-05-28 16:50:20
【问题描述】:
我已经接近了我想要实现的目标,但并不完全。我想组合框显示所有部门,但只显示绑定到员工的部门。希望有人能看到我的错误在哪里。 WPF 和 Caliburn 的新手。
这是我的模型:
public class Department
{
public int IdDept { get; set; }
public string NameDept { get; set; }
}
public class Employee
{
public int IdEmployee { get; set; }
public string NameEmployee { get; set; }
public int DeptId { get; set; }
}
视图模型:
public class ShellViewModel : PropertyChangedBase
{
private BindableCollection<Employee> _employees = new BindableCollection<Employee>();
private BindableCollection<Department> _departments= new BindableCollection<Department>();
public BindableCollection<Employee> Employees
{
get{return _employees;}
set
{ _employees = value; NotifyOfPropertyChange(() => Employees);}
}
public BindableCollection<Department> Departments
{
get{return _departments;}
set{_departments = value;
NotifyOfPropertyChange(() => Departments);}
}
public ShellViewModel()
{// simulated data from DB
Employees.Add(new Employee { IdEmployee = 1, NameEmployee = "Jim", DeptId = 1 });
Employees.Add(new Employee { IdEmployee = 2, NameEmployee = "Mike", DeptId = 3 });
Departments.Add(new Department { IdDept = 1, NameDept = "Accounting" });
Departments.Add(new Department { IdDept = 2, NameDept = "Human Resource" });
Departments.Add(new Department { IdDept = 2, NameDept = "IT" });
}
}
}
查看:
<Grid>
<ListBox x:Name="Employees" HorizontalAlignment="Left" Height="260" Margin="83,52,0,0" VerticalAlignment="Top" Width="612">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<TextBox Text="{Binding NameEmployee}" Grid.Column="1" />
<TextBlock Text="{Binding IdEmployee}" Grid.Column="0"/>
<ComboBox Grid.Column="2"
ItemsSource="{Binding DataContext.Departments,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type Window}}}"
SelectedValuePath="DeptId"
DisplayMemberPath="NameDept"
SelectedValue="{Binding IdDept}"/>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
【问题讨论】:
标签: c# wpf data-binding combobox caliburn.micro