我需要用我的部门列表填充我的组合框并将我的组合框的选定项目设置为我的员工部门
模特部门
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
模型员工:
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Department Department { get; set; }
}
视图模型
public class ViewModel
{
public Employee Employee { get; set; }
public ObservableCollection<Department> Departments{ get; set; }
public ViewModel()
{
Employee new Employee ()
{
FirstName = "Harry",
LastName = "Park",
Department = new Department { Id = 1, Name = "Department 2" },
};
Departments= new ObservableCollection<Department> ()
{
new Department{ Id=1, Name="Department 1" },
new Department{ Id=2, Name="Department 2" },
new Department{ Id=2, Name="Department 3" },
};
}
XAML
<Grid DataContext="{StaticResource ViewModel
<ComboBox
ItemsSource="{Binding Department
SelectedValue="{Binding Employee.Department
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
你能帮助我吗?
答案 0 :(得分:0)
此代码工作 - 已经过测试:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Department Department { get; set; }
}
public class ViewModel
{
public Employee Employee { get; set; }
public ObservableCollection<Department> Departments { get; set; }
public ViewModel()
{
Departments = new ObservableCollection<Department>()
{
new Department{ Id=1, Name="Department 1" },
new Department{ Id=2, Name="Department 2" },
new Department{ Id=2, Name="Department 3" },
};
Employee = new Employee()
{
FirstName = "Harry",
LastName = "Park",
Department = Departments.First(),
};
}
<Grid>
<ComboBox Height="30"
ItemsSource="{Binding Departments}"
SelectedValue="{Binding Employee.Department}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
答案 1 :(得分:0)
<Grid DataContext="{StaticResource ViewModel}">
<ComboBox ItemsSource="{Binding Departments}"
SelectedItem="{Binding Employee.Department}"
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>