【发布时间】:2017-05-14 04:00:31
【问题描述】:
我制作了一个小示例项目来进行可视化。我有一个项目,其中包含许多相互影响的组合框,我需要将其应用于。
我有两个 ComboBox,Numbers 和 Colors。
Numbers 中的 SelectedItem 改变了 Items 和 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。
标签: c# wpf visual-studio xaml combobox