实现的功能是:wpf中多个下拉框绑定同一个列表数据源,其中一个下拉框选择了其中一个项,其他下拉框就不能选择该项了(这个功能已经实现),然后我需要在下面代码基础上增加二个新功能:① 添加一个特定的选项,每个下拉框能够同时选择该特定选项,② 复位按钮点击后,所有的下拉框选择默认1,并且所有下拉框的选项都要初始化;
html主要实现代码:
<ItemsControl ItemsSource="{Binding FeedingOrderItems}" Grid.Row="2" Grid.Column="1" Margin="0,0,20,0">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="6" Columns="8"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="White" BorderBrush="Gray" BorderThickness="1" CornerRadius="4" Padding="5" Margin="5">
<Grid>
<!-- 定义两列,一列用于 CheckBox,另一列用于 ComboBox -->
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding CheckText}" Margin="5" VerticalAlignment="Center" Grid.Column="0"/>
<TextBox Tag="{Binding TextTag}" Text="{Binding TextText}" Margin="5" Width="30" Panel.ZIndex="2" HorizontalAlignment="Left" Grid.Column="1"></TextBox>
<ComboBox Tag="{Binding ComboxTag}" SelectedItem="{Binding SelectedItem}" Panel.ZIndex="1" DisplayMemberPath="Name" SelectedValuePath="Id" Margin="5" VerticalAlignment="Center" Grid.Column="1" HorizontalAlignment="Stretch"/>
<CheckBox IsChecked="{Binding IsOldChecked}" Content="{Binding OldCheckText}" Margin="5" VerticalAlignment="Center" Grid.Column="0" Grid.Row="1"/>
<ComboBox ItemsSource="{Binding PriorityComboBoxItems}" SelectedItem="{Binding PrioritySelectedItem}" Margin="5" VerticalAlignment="Center" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Stretch"/>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- 保存按钮 -->
<Button Content="数据复位" Width="80" Height="40" Grid.Row="5" Grid.Column="1" Margin="0,10,140,10" HorizontalAlignment="Right" VerticalAlignment="Center" Background="LightGray" Click="ResetData_Click"/>
<!-- 保存按钮 -->
<Button Content="保存" Width="80" Height="40" Grid.Row="5" Grid.Column="1" Margin="0,10,20,10" HorizontalAlignment="Right" VerticalAlignment="Center" Background="LightGray" Click="SaveConfig_Click"/>
后台实现的代码:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using IZeroVision.Core.Helper;
using MahApps.Metro.Controls;
using static ShortageMonitoringSystem.SetConfigWindow;
namespace ShortageMonitoringSystem
{
public class FeedingOrderItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private string _cbTag;
public string ComboxTag
{
get => _cbTag;
set
{
_cbTag = value;
RaisePropertyChanged("ComboxTag");
}
}
private string _textTag;
public string TextTag
{
get => _textTag;
set
{
_textTag = value;
RaisePropertyChanged("TextTag");
}
}
private string _textText;
public string TextText
{
get => _textText;
set
{
_textText = value;
RaisePropertyChanged("TextText");
}
}
private Item _selectedItem;
public Item SelectedItem
{
get => _selectedItem;
set
{
_selectedItem = value;
RaisePropertyChanged("SelectedItem");
}
}
private bool _isChecked;
public bool IsChecked
{
get => _isChecked;
set
{
_isChecked = value;
RaisePropertyChanged("IsChecked");
}
}
public string _Checktext;
public string CheckText
{
get => _Checktext;
set
{
_Checktext = value;
RaisePropertyChanged("CheckText");
}
}
private bool _isOldChecked;
public bool IsOldChecked
{
get => _isOldChecked;
set
{
_isOldChecked = value;
RaisePropertyChanged("IsOldChecked");
}
}
public string _OldChecktext;
public string OldCheckText
{
get => _OldChecktext;
set
{
_OldChecktext = value;
RaisePropertyChanged("OldCheckText");
}
}
public ObservableCollection<string> ComboBoxItems { get; set; }
private string _priorityselectedItem;
public string PrioritySelectedItem
{
get => _priorityselectedItem;
set
{
_priorityselectedItem = value;
RaisePropertyChanged("PrioritySelectedItem");
}
}
public ObservableCollection<string> PriorityComboBoxItems { get; set; }
}
/// <summary>
/// SetConfigWindow.xaml 的交互逻辑
/// </summary>
public partial class SetConfigWindow : MetroWindow, INotifyPropertyChanged
{
private ObservableCollection<FeedingOrderItem> _feedingOrderItems;
public ObservableCollection<FeedingOrderItem> FeedingOrderItems
{
get => _feedingOrderItems;
set
{
_feedingOrderItems = value;
RaisePropertyChanged("FeedingOrderItems");
}
}
private Solution _solution;
/// <summary>
/// 项目
/// </summary>
public Solution Solution
{
get { return _solution; }
set
{
_solution = value;
for (int i = 0; i < FeedingOrderItems.Count; i++)
{
FeedingOrderItems[i].TextText = _solution.FeedingOrderItemSetList[i].TextText;
FeedingOrderItems[i].SelectedItem = _solution.FeedingOrderItemSetList[i].SelectedItem;
FeedingOrderItems[i].IsChecked = _solution.FeedingOrderItemSetList[i].IsChecked;
FeedingOrderItems[i].IsOldChecked = _solution.FeedingOrderItemSetList[i].IsOldChecked;
FeedingOrderItems[i].PrioritySelectedItem = _solution.FeedingOrderItemSetList[i].PrioritySelectedItem;
}
NewSupplementTime = _solution.NewSupplementTime;
OldSupplementTime = _solution.OldSupplementTime;
}
}
private double _NewSupplementTime;
public double NewSupplementTime
{
get => _NewSupplementTime;
set
{
_NewSupplementTime = value;
RaisePropertyChanged("NewSupplementTime");
}
}
private double _OldSupplementTime;
public double OldSupplementTime
{
get => _OldSupplementTime;
set
{
_OldSupplementTime = value;
RaisePropertyChanged("OldSupplementTime");
}
}
public ObservableCollection<Item> ItemsSource { get; set; }
public Dictionary<string, Item> SelectedItems { get; set; }
public List<ComboBox> ComboBoxes { get; set; }
public SetConfigWindow()
{
InitializeComponent();
List<string> comboxlist = new List<string>();
for (int i = 1; i < 45; i++)
{
comboxlist.Add(i.ToString());
}
FeedingOrderItems = new ObservableCollection<FeedingOrderItem>();
for (int i = 1; i < 45; i++)
{
FeedingOrderItems.Add(new FeedingOrderItem
{
ComboxTag = $"CBTag{i}",
TextTag = $"TextTag{i}",
SelectedItem = new SetConfigWindow.Item { Id = i, Name = $"{i}" },
CheckText = $"机器{i}启用",
IsChecked = false,
ComboBoxItems = new ObservableCollection<string>(comboxlist),
OldCheckText = "旧料补充",
IsOldChecked = false,
PriorityComboBoxItems = new ObservableCollection<string>() { "主源头泵", "次源头泵" },
PrioritySelectedItem = "主源头泵"
});
}
}
public void LoadComBoBox()
{
for (int i = 0; i < ComboBoxes.Count; i++)
{
var comboBox = FindComboBoxByTag(_solution.FeedingOrderItemSetList[i].ComboxTag);
var selectedItem = _solution.FeedingOrderItemSetList[i].SelectedItem as Item;
string tag = comboBox.Tag as string;
if (selectedItem != null)
{
string[] singleArray = tag.Split('g');
string number = singleArray[1];
comboBox.SelectedValue = _solution.FeedingOrderItemSetList[i].TextText;
FindTextBoxByTag($"TextTag{number}").Text = FindComboBoxByTag(tag).Text = _solution.FeedingOrderItemSetList[i].TextText;
}
}
}
private void SetCollectionView(ComboBox cmb)
{
var view = CollectionViewSource.GetDefaultView(ItemsSource);
view.Filter = (item) => !SelectedItems.ContainsValue(item as Item);
cmb.ItemsSource = view;
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox comboBox = sender as ComboBox;
var selectedItem = comboBox.SelectedItem as Item;
string tag = comboBox.Tag as string;
// 确保sender是一个ComboBox
if (comboBox.Text != "")
{
string[] singleArray = tag.Split('g');
string number = singleArray[1];
FeedingOrderItems[Convert.ToInt32(number) - 1].TextText = FindTextBoxByTag($"TextTag{number}").Text = FindComboBoxByTag(tag).Text;
}
if (selectedItem != null)
{
List<string> singleCharList = tag.ToCharArray()
.Select(c => c.ToString())
.ToList();
string number = "";
if (tag.Length == 7)
{
number = singleCharList[5] + singleCharList[6];
}
else if (tag.Length == 6)
{
number = singleCharList[5];
}
FeedingOrderItems[Convert.ToInt32(number) - 1].SelectedItem = selectedItem;
}
if (selectedItem != null)
{
if (SelectedItems.ContainsKey(tag))
{
SelectedItems.Remove(tag);
}
SelectedItems.Add(tag, selectedItem);
foreach (var cmb in ComboBoxes)
{
if (cmb != comboBox)
{
((ICollectionView)cmb.ItemsSource).Refresh();
}
}
}
}
private ComboBox FindComboBoxByTag(string tagToFind)
{
var comboBoxes = VisualTreeHelperExtensions.GetDescendantControlsOfType(this, typeof(ComboBox))
.Cast<ComboBox>();
ComboBox comboBox1 = new ComboBox();
foreach (var comboBox in comboBoxes)
{
if ((string)comboBox.Tag == tagToFind)
{
// 这里可以进行进一步的处理
// 例如,设置样式、获取/设置属性等
//comboBox.Background = Brushes.Red;
comboBox1 = comboBox;
}
}
return comboBox1;
}
private TextBox FindTextBoxByTag(string tagToFind)
{
var textBoxes = VisualTreeHelperExtensions.GetDescendantControlsOfType(this, typeof(TextBox))
.Cast<TextBox>();
TextBox textBox1 = new TextBox();
foreach (var comboBox in textBoxes)
{
if ((string)comboBox.Tag == tagToFind)
{
// 这里可以进行进一步的处理
// 例如,设置样式、获取/设置属性等
//comboBox.Background = Brushes.Red;
textBox1 = comboBox;
}
}
return textBox1;
}
private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
{
ComboBoxes = new List<ComboBox>();
for (int i = 0; i < _solution.FeedingOrderItemSetList.Count; i++)
{
ComboBoxes.Add(FindComboBoxByTag(_solution.FeedingOrderItemSetList[i].ComboxTag));
}
SelectedItems = new Dictionary<string, Item>();
foreach (var cmb in ComboBoxes)
{
cmb.SelectionChanged += ComboBox_SelectionChanged;
SetCollectionView(cmb);
}
LoadComBoBox();
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private void ResetData_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < FeedingOrderItems.Count; i++)
{
FeedingOrderItems[i].SelectedItem = new SetConfigWindow.Item { Id = 1, Name = "1" };
FeedingOrderItems[i].TextText = FindTextBoxByTag($"TextTag{i + 1}").Text = "1";
FeedingOrderItems[i].IsChecked = false;
FeedingOrderItems[i].IsOldChecked = false;
FeedingOrderItems[i].PrioritySelectedItem = "主源头泵";
}
}
private void SaveConfig_Click(object sender, RoutedEventArgs e)
{
try
{
if (_solution != null)
{
for (int i = 0; i < FeedingOrderItems.Count; i++)
{
if (FeedingOrderItems[i].TextText == "45")
{
MessageBox.Show("45 为临时值,请更改……");
return;
}
_solution.FeedingOrderItemSetList[i].TextText = FeedingOrderItems[i].TextText;
_solution.FeedingOrderItemSetList[i].SelectedItem = FeedingOrderItems[i].SelectedItem;
_solution.FeedingOrderItemSetList[i].IsChecked = _feedingOrderItems[i].IsChecked;
_solution.FeedingOrderItemSetList[i].IsOldChecked = _feedingOrderItems[i].IsOldChecked;
_solution.FeedingOrderItemSetList[i].PrioritySelectedItem = _feedingOrderItems[i].PrioritySelectedItem;
}
_solution.NewSupplementTime = _NewSupplementTime;
_solution.OldSupplementTime = _OldSupplementTime;
}
SerializeHelper.WriteEncryption("IZeroVision.sln", _solution);
MessageBox.Show("保存成功");
}
catch (Exception ex)
{
MessageBox.Show("保存失败,异常原因:" + ex.Message);
}
}
[Serializable]
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
}
public static class VisualTreeHelperExtensions
{
public static IEnumerable<DependencyObject> GetDescendantControlsOfType(DependencyObject root, Type type)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
var child = VisualTreeHelper.GetChild(root, i);
if (child.GetType() == type)
yield return child;
foreach (var descendant in GetDescendantControlsOfType(child, type))
yield return descendant;
}
}
}
}
solution.cs类的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShortageMonitoringSystem
{
[Serializable]
public class FeedingOrderItemSet
{
private string _cbTag;
public string ComboxTag
{
get => _cbTag;
set
{
_cbTag = value;
}
}
private string _textTag;
public string TextTag
{
get => _textTag;
set
{
_textTag = value;
}
}
private string _textText;
public string TextText
{
get => _textText;
set
{
_textText = value;
}
}
private SetConfigWindow.Item _selectedItem;
public SetConfigWindow.Item SelectedItem
{
get => _selectedItem;
set
{
_selectedItem = value;
}
}
//是否启用
private bool _isChecked;
public bool IsChecked
{
get => _isChecked;
set
{
_isChecked = value;
}
}
//第一次执行
[NonSerialized]
public bool _isFirst;
public bool IsFirst
{
get => _isFirst;
set
{
_isFirst = value;
}
}
public int _index;
public int Index
{
get => _index;
set
{
_index = value;
}
}
[NonSerialized]
public bool _isWork;
public bool IsWork
{
get => _isWork;
set
{
_isWork = value;
}
}
//旧料补料
private bool _isOldChecked;
public bool IsOldChecked
{
get => _isOldChecked;
set
{
_isOldChecked = value;
}
}
//是否异常
private bool _isError;
public bool IsError
{
get => _isError;
set
{
_isError = value;
}
}
//主次泵
private string _priorityselectedItem;
public string PrioritySelectedItem
{
get => _priorityselectedItem;
set
{
_priorityselectedItem = value;
}
}
}
[Serializable]
public class Solution
{
private List<FeedingOrderItemSet> _FeedingOrderItemSetList;
public List<FeedingOrderItemSet> FeedingOrderItemSetList
{
get => _FeedingOrderItemSetList;
set
{
_FeedingOrderItemSetList = value;
}
}
private double _NewSupplementTime;
public double NewSupplementTime
{
get => _NewSupplementTime;
set
{
_NewSupplementTime = value;
}
}
private double _OldSupplementTime;
public double OldSupplementTime
{
get => _OldSupplementTime;
set
{
_OldSupplementTime = value;
}
}
/// <summary>
/// 按 SelectedItem 转换为 int 后按升序排序
/// </summary>
public void SortFeedingOrderItemSetList(out List<FeedingOrderItemSet> sortresultlist)
{
sortresultlist = _FeedingOrderItemSetList
.OrderBy(item => ConvertToInt(item.SelectedItem.Name))
.ToList();
}
/// <summary>
/// 将 SelectedItem 转换为 int
/// </summary>
/// <param name="selectedItem">字符串类型的 SelectedItem</param>
/// <returns>转换后的 int 值</returns>
private int ConvertToInt(string selectedItem)
{
if (int.TryParse(selectedItem, out int result))
{
return result;
}
else
{
// 如果转换失败,可以根据需求决定抛出异常或返回一个默认值
throw new FormatException($"Unable to convert '{selectedItem}' to an integer.");
}
}
public Solution()
{
_FeedingOrderItemSetList = new List<FeedingOrderItemSet>();
for (int i = 1; i < 45; i++)
{
if (i % 2 == 0)
{
_FeedingOrderItemSetList.Add(new FeedingOrderItemSet
{
ComboxTag = $"CBTag{i}",
TextTag = $"TextTag{i}",
TextText = "1",
IsChecked = false,
SelectedItem = new SetConfigWindow.Item { Id = 1, Name = "1" },
IsOldChecked = false,
PrioritySelectedItem = "主源头泵",
IsFirst=false,
Index=i,
IsError=false
});
}
else
{
_FeedingOrderItemSetList.Add(new FeedingOrderItemSet
{
ComboxTag = $"CBTag{i}",
TextTag = $"TextTag{i}",
TextText = "1",
IsChecked = true,
SelectedItem = new SetConfigWindow.Item { Id = 2, Name = "2" },
IsOldChecked = true,
PrioritySelectedItem = "次源头泵",
IsFirst = false,
Index = i,
IsError = false
});
}
}
_NewSupplementTime = 0;
_OldSupplementTime = 0;
}
}
}