WPF组合框与外部源绑定

时间:2018-05-14 19:36:31

标签: c# wpf data-binding combobox

我在<ComboBox Name="LeaderTextBox" Grid.Column="6" Grid.Row="2" MinWidth="150" SelectedItem="{Binding Path=ProjectLeader}" DisplayMemberPath="Name" Margin="5" /> 上遇到数据绑定问题。组合框不显示最初设置的项目。

我的.xaml:

ItemSource

在代码中,我设置了LeaderTextBox.ItemsSource = service.GetAllEmployee(); ,如下所示:

service.GetAllEmployee()

ProjectLeader返回一个列表/数组的员工,它们也被填充到组合框中,这意味着我可以选择它们。

我的问题是,如果我为[Serializable] [DataContract(Namespace = "Shared", IsReference = true)] public class Employee { public Employee() { this.Projects = new List<Project>(); } [DataMember] public int? ID { get; set; } [DataMember] public String Name { get; set; } [DataMember] public String JobDescription { get; set; } [DataMember] public String Department { get; set; } [DataMember] public String DirectDialing { get; set; } [DataMember] public bool Status { get; set; } [DataMember] public virtual Project LeaderOfProject { get; set; } [DataMember] public virtual List<Project> Projects { get; set; } public override string ToString() { return ID + " " + Name + " " + JobDescription + " " + Department + " " + DirectDialing; } } [Serializable] [DataContract(Namespace = "Shared", IsReference = true)] public class Project { public Project() { this.EmployeesWorkingOnProject = new List<Employee>(); this.ProjectSteps = new List<ProjectStep>(); } [DataMember] public int? ID { get; set; } [DataMember] public String Titel { get; set; } [DataMember] public DateTime StartDate { get; set; } [DataMember] public DateTime EndDate { get; set; } [DataMember] public String Description { get; set; } [DataMember] public Employee ProjectLeader { get; set; } [DataMember] public bool Status { get; set; } [DataMember] public virtual List<Employee> EmployeesWorkingOnProject { get; set; } [DataMember] public virtual List<ProjectStep> ProjectSteps { get; set; } public override string ToString() { return ID +" "+ Titel+" "+StartDate+ " "+ EndDate +" "+ Description; } } 设置了值,则不会显示。我在那里错过了什么?

参考模型:

ON DELETE

1 个答案:

答案 0 :(得分:0)

您无法通过不在组合框中的项目选择组合框的项目。

右:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var paul = new Employee { Name = "Paul" };
        LeaderTextBox.ItemsSource = new List<Employee>()
        {
            new Employee {Name = "Bob" },
            paul,
            new Employee {Name = "Alex" },
        };
        ProjectLeader = paul;
    }

错:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        LeaderTextBox.ItemsSource = new List<Employee>()
        {
            new Employee {Name = "Bob" },
            new Employee { Name = "Paul" },
            new Employee {Name = "Alex" },
        };
        ProjectLeader = new Employee {Name = "Paul" };
    }