我已经做了一个小例子项目可视化。我有一个项目,其中包含许多组合框,这些组合框会影响到我需要应用的其他组合框。绑定ComboBox以更改另一个带有XAML的组合框?
我有两个组合框,编号和颜色。
的的SelectedItem在号改变项目 & 的SelectedItem在颜色。
如何使用WPF XAML绑定ItemSource和SelectedItem?
使用ICollection?
从ObservableCollection中添加/删除项目?
创建一个列表作为集合的ItemSource?
单独使用Add()/ Remove()更改项目或将整个 ItemSource更换为另一个项目?
comboBoxNumers = 1,2,3,4
comboBoxColors =红,绿,蓝
- 1→红
- 2→绿色
- 3 →蓝色
4→去除红色,绿色。添加黄色。
1,2或3→删除黄色(如果存在)。添加红色,绿色(如果不存在)。
1→红
2→绿色
4→黄色(删除红/绿)
老C#的方式我一直在使用:
填充组合框
List<string> NumbersItems = new List<string>() { "1", "2", "3", "4" };
NumbersItems.ForEach(i => comboBoxNumbers.Items.Add(i));
List<string> ColorsItems = new List<string>() { "Red", "Green", "Blue" };
ColorsItems.ForEach(i => comboBoxColors.Items.Add(i));
1→红
// Numbers 1
if ((string)comboBoxNumbers.SelectedItem == "1")
{
// Remove Yellow if Exists
if (comboBoxColors.Items.Contains("Yellow")) {
comboBoxColors.Items.RemoveAt(comboBoxColors.Items.IndexOf("Yellow"));
}
// Add Red if Does Not Exist
if (!comboBoxColors.Items.Contains("Red")) {
comboBoxColors.Items.Insert(0, "Red");
}
// Select Red
comboBoxColors.SelectedItem = "Red";
}
2→绿色
// Numbers 2
if ((string)comboBoxNumbers.SelectedItem == "2")
{
// Remove Yellow if Exists
if (comboBoxColors.Items.Contains("Yellow")) {
comboBoxColors.Items.RemoveAt(comboBoxColors.Items.IndexOf("Yellow"));
}
// Add Green if Does Not Exist
if (!comboBoxColors.Items.Contains("Green")) {
comboBoxColors.Items.Insert(1, "Green");
}
// Select Green
comboBoxColors.SelectedItem = "Green";
}
4→黄色(删除红/绿)
// Numbers 4
if ((string)comboBoxNumbers.SelectedItem == "4")
{
// Remove Red if Exists
if (comboBoxColors.Items.Contains("Red")) {
comboBoxColors.Items.RemoveAt(comboBoxColors.Items.IndexOf("Red"));
}
// Remove Green if Exists
if (comboBoxColors.Items.Contains("Green")) {
comboBoxColors.Items.RemoveAt(comboBoxColors.Items.IndexOf("Green"));
}
// Add Yellow if Does Not Exist
if (!comboBoxColors.Items.Contains("Yellow")) {
comboBoxColors.Items.Insert(0, "Yellow");
}
// Select Yellow
comboBoxColors.SelectedItem = "Yellow";
}
的方法写一个视图模型。 “从ObservableCollection添加/删除项目”。将集合绑定到'ComboBox.ItemsSource',不要直接触摸'Items'。 –