我有一个带有ComboBox的ListBox。 ListBox的项目源已设置为ObservableCollection。
如何将ComboBox的ItemSource设置为另一个ObservableCollection,它不是ListBox视图模型的一部分,而是在视图模型内部。
这是我的示例代码:
public class MyViewModel
{
public ObservableCollection<Employee> Employees { get; set; }
public ObservableCollection<string> Designations { get; set; }
public MyViewModel()
{
Employees = ReadEmolpyeesFromDB();
Designations = ReadDesignationsFromDB();
}
private ObservableCollection<Employee> ReadEmolpyeesFromDB()
{
// read DB and return ObservableCollection<Employee>
}
private ObservableCollection<string> ReadDesignationsFromDB()
{
// read DB and return ObservableCollection<string>
}
}
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public string Designation { get; set; }
}
<ListBox.ItemTemplate>
<DataTemplate>
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
<ColumnDefinition Width="40" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Name}" />
<TextBox Text="{Binding Age}" Grid.Column="1"/>
<ComboBox SelectedValue="{Binding Designation}" Grid.Column="2"
ItemsSource="{Binding Designations}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我正在尝试将Designations
绑定为ComboBox ItemSource。但是ComboBox的SelectedValue / Text绑定到Designation
ObservableCollection<Employee> Employees
上