我有这个接近我想要实现的目标,但不完全是。我想在组合框中显示所有部门,但只显示绑定到员工的部门。希望有人能看到我的错误所在。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>
在 SelectedValuePath 和 SelectedValue 绑定中切换属性名称:
SelectedValuePath="IdDept"
SelectedValue="{Binding DeptId}"
SelectedValuePath 应该是存在于 ComboBox.ItemsSource 元素中的属性 - 因此Department.IdDept
SelectedValue 应该是 ComboBox DataContext(Employee 对象(中存在的属性 - 因此Employee.DeptId