要绑定的数据结构如下,一个Category包含多个SubCategory:
public class Category
{
public string Name { get; set; }
public ObservableCollection<SubCategory> SubCategories { get; set; }
}
public class SubCategory
{
public int Id { get; set; }
public string SubCategoryName { get; set; }
}
Code-behind初始化测试数据:
public partial class AssetEditor : Window
{
public ObservableCollection<Category> CategorieCollection { get; set; }
public AssetEditor()
{
InitializeComponent();
CategorieCollection = new ObservableCollection<Category>();
CategorieCollection.Add(new Category()
{
Name = "Cate1",
SubCategories = new ObservableCollection<SubCategory>()
});
CategorieCollection.Add(new Category()
{
Name = "Cate2",
SubCategories = new ObservableCollection<SubCategory>()
});
CategorieCollection[0].SubCategories.Add(new SubCategory()
{
Id = 0,
SubCategoryName = "sub1"
});
CategorieCollection[1].SubCategories.Add(new SubCategory()
{
Id = 0,
SubCategoryName = "sub2"
});
cmbCategoryName.DataContext = CategorieCollection;
}
}
XAML里绑定:
<ComboBox Grid.Row="0" Grid.ColumnSpan="2" Grid.Column="1" Name="cmbCategoryName"
ItemsSource="{Binding}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedItem="{Binding Path=SubCategories}" />
<ComboBox Grid.Row="0" Grid.Column="5" Grid.ColumnSpan="3" Name="cmbSubCategory"
DataContext="{Binding ElementName=cmbCategoryName,Path=Items,Mode=OneWay}"
ItemsSource="{Binding Path=SubCategories, Mode=OneWay}"
DisplayMemberPath="SubCategoryName"
SelectedValuePath="Id" />
当cmbCategoryName选中的Category改变,cmbSubCategory的 SubCategory集合也会随之改变