WPF将SelectedItem的嵌套属性绑定到Combobox TwoWay

时间:2018-02-02 12:20:02

标签: c# wpf xaml combobox selecteditem

商业模式:

public class Employe : INotifyPropertyChanged
{
    public int EmployeId { get; set; }
    public string EmployeName { get; set; }
    public Department EmployeDepartment { get; set; }
}
public class Department : INotifyPropertyChanged
{
    public int DepartmentId { get; set; }
    public string DepartmentName { get; set; }
}

MainWindow中的List属性:

    public List<Department> Departments { get; set; } = new List<Department>();
    public List<Employe> Employes { get; set; } = new List<Employe>();

样本初始化:

        var office = new Department { DepartmentId = 1, DepartmentName = "Office" };
        var admin = new Department { DepartmentId = 2, DepartmentName = "Administration" };
        var purchasing = new Department { DepartmentId = 3, DepartmentName = "Purchasing" };
        Departments.Add(office);
        Departments.Add(admin);
        Departments.Add(purchasing);
        Employes.Add(new Employe { EmployeId = 1, EmployeName = "John", EmployeDepartment = office });
        Employes.Add(new Employe { EmployeId = 2, EmployeName = "Sue", EmployeDepartment = admin });
        Employes.Add(new Employe { EmployeId = 3, EmployeName = "Bill", EmployeDepartment = admin });
        Employes.Add(new Employe { EmployeId = 4, EmployeName = "Linda", EmployeDepartment = purchasing });
        Employes.Add(new Employe { EmployeId = 5, EmployeName = "Tom", EmployeDepartment = purchasing });
        Employes.Add(new Employe { EmployeId = 6, EmployeName = "Mick", EmployeDepartment = purchasing });

首先我显示雇员名单(工作正常)

        <ListBox x:Name="lbEmployes" ItemsSource="{Binding Employes}" DisplayMemberPath="EmployeName" />

现在我想通过使用DataTemplate来展示SelectedItem的详细视图:

        <ContentControl Content="{Binding ElementName=lbEmployes, Path=SelectedItem}" ContentTemplate="{StaticResource EmployesTemplate}" />

的DataTemplate:

    <DataTemplate DataType="{x:Type local:Employe}" x:Key="EmployesTemplate">
        <StackPanel>
            <TextBlock Text="{Binding Path=EmployeId}"></TextBlock>
            <TextBox Text="{Binding Path=EmployeName}"></TextBox>
            <ComboBox ItemsSource="{Binding Path=EmployeDepartment, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Department" DisplayMemberPath="DepartmentName" />
        </StackPanel>
    </DataTemplate>

ID和名称工作正常。如何修复Combobox?如何绑定ItemsSource和SelectedItem?

完整的SourceCode:https://gist.github.com/LwServices/a88818e52a612790e3785e308f5ad2ce

1 个答案:

答案 0 :(得分:1)

Combobox的正确绑定是:

            <ComboBox ItemsSource="{Binding Departments, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}" DisplayMemberPath="DepartmentName" SelectedItem="{Binding Path=EmployeDepartment}" />