我需要使用数据绑定(bind)创建 3 个级联组合框(A、B 和 C)。从我看到的示例中,我能够获得两个工作(A 和 B),但我不确定如何连接 ComboBox C,其 ItemsSource 应该取决于 ComboBox B 中所做的选择。所以,就像有对于组合框 A 中显示的每个类别,在组合框 B 中显示一组原因,我需要在组合框 C 中为组合框 B 中显示的每个原因显示一组子原因。随着选择的变化,基础下拉列表值也会发生变化。我希望这是有道理的。有没有办法绑定(bind)到 ViewModel 属性来实现这个或???。
XAML
<ComboBox x:Name="cbxA"
ItemsSource="{Binding ProjectCategoryList}"
SelectedIndex="{Binding Path=SelectedProject.Category}"
DisplayMemberPath="Category"/>
<ComboBox x:Name="cbxB"
ItemsSource="{Binding ElementName=cbxA, Path=SelectedItem.Reasons}"
Text="{Binding Path=SelectedProject.Reason}" DisplayMemberPath="Name"/>
<ComboBox x:Name="cbxC"
ItemsSource="{Binding ElementName=cbxB, Path=SelectedItem.SubReasons}"
Text="{Binding Path=SelectedProject.SubReason}"/>
ViewModel
private Project selectedProject;
public Project SelectedProject
{
get { return selectedProject; }
set
{
if(selectedProject != value)
{
selectedProject = value;
NotifyPropertyChanged("SelectedProject");
}
}
}
public List<ProjectCategory> ProjectCategoryList
{
get
{
return new List<ProjectCategory>()
{
new ProjectCategory
{
Category = "One",
Reasons = new List<Reason>
{
new Reason() { Name = "A", SubReasons = new List<String> { "1", "2", "3" }},
new Reason() { Name = "B", SubReasons = new List<String> { "4", "5", "6" }},
new Reason() { Name = "C", SubReasons = new List<String> { "7", "8", "9" }},
}
},
new ProjectCategory
{
Category = "Two",
Reasons = new List<Reason>
{
new Reason() { Name = "D", SubReasons = Enumerable.Empty<string>()},
new Reason() { Name = "E", SubReasons = Enumerable.Empty<string>()},
new Reason() { Name = "F", SubReasons = Enumerable.Empty<string>()},
}
},
new ProjectCategory
{
Category = "Three",
Reasons = new List<Reason>
{
new Reason() { Name = "J", SubReasons = Enumerable.Empty<string>()},
new Reason() { Name = "K", SubReasons = Enumerable.Empty<string>()},
}
},
};
}
}
ProjectCategory.cs
public class ProjectCategory
{
public string Category { get; set; }
public IEnumerable<Reason> Reasons { get; set; }
}
public class Reason
{
public string Name { get; set; }
public IEnumerable<string> SubReasons { get; set; }
}
最佳答案
Reasons
ProjectCategory
的属性(property)类应返回 IEnumerable<Reason>
而不是 IEnumerable<string>
和 Reason
类应包含 Name
(或 Reason
)类型的属性 string
和 IEnumerable<string>
子原因。
然后可以绑定(bind)cbxC
一样的方法:
<ComboBox x:Name="cbxA"
ItemsSource="{Binding ProjectCategoryList}"
SelectedIndex="{Binding Path=SelectedProject.Category}"
DisplayMemberPath="Category"/>
<ComboBox x:Name="cbxB"
ItemsSource="{Binding ElementName=cbxA, Path=SelectedItem.Reasons}"
DisplayMemberPath="Name" />
<ComboBox x:Name="cbxC"
ItemsSource="{Binding ElementName=cbxb, Path=SelectedItem.SubReasons}" />
public class ProjectCategory
{
public string Category { get; set; }
public IEnumerable<Reason> Reasons { get; set; }
}
public class Reason
{
public string Name { get; set; }
public IEnumerable<string> SubReasons { get; set; }
}
关于c# - 可以级联两个ComboBox,需要级联第三个ComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46473214/