m0_58844937 2024-10-19 10:23 采纳率: 94.3%
浏览 9

wpf中多个下拉框绑定同一个列表数据源,其中一个下拉框选择了其中一个项,其他下拉框就不能选择该项了

实现的功能是: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;
        }
    }
}
  • 写回答

1条回答 默认 最新

  • 无疆76 2024-10-19 10:24
    关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    看起来你想要增加两个功能:① 添加一个特定的选项,每个下拉框能够同时选择该特定选项;② 复位按钮点击后,所有下拉框选择默认第一项,并且所有下拉框的选项都要初始化。基于你的代码,我将为你提供修改建议:

    添加一个特定的选项

    为了在组合框(ComboBox)中添加一个特定的选项,并在所有下拉框中都可以选择,你可以在初始化FeedingOrderItem时,为ComboBoxItems集合中添加这个特定选项。例如,可以添加一个选项名为"特殊选项"或"特定选项"。然后,在ComboBoxSelectionChanged事件中,确保当这个特定选项被选中时,其他下拉框不会受到影响(即不触发其他下拉框的联动选择)。

    复位按钮点击,初始化下拉框

    对于复位按钮点击后,所有下拉框选择默认第一项并初始化,你可以在ResetData_Click方法中遍历所有下拉框并设置其默认选项。你可以将默认选项设置为第一项,例如将每个FeedingOrderItemTextTextSelectedItem设置为第一项的值。对于联动选择功能,你可能需要在复位时重置相关的逻辑以保证不会触发其他下拉框的联动选择。

    以下是修改后的部分代码示例:

    在初始化FeedingOrderItem时添加特定选项

    在初始化FeedingOrderItem时,为ComboBoxItems添加一个特定选项。这里以添加名为"特殊选项"的项目为例:

    public class FeedingOrderItem : INotifyPropertyChanged
    {
        // ... 其他代码 ...
    
        public ObservableCollection<string> ComboBoxItems { get; set; }
        // 在初始化时添加特定选项到 ComboBoxItems 集合中
        public FeedingOrderItem()
        {
            // ... 其他初始化代码 ...
            ComboBoxItems = new ObservableCollection<string> { /* 其他选项 */, "特殊选项" }; // 添加特殊选项到集合末尾或其他位置
        }
    }
    

    修改ResetData_Click方法以设置默认选项

    ResetData_Click方法中设置所有下拉框的默认选项:

    private void ResetData_Click(object sender, RoutedEventArgs e)
    {
        // 设置所有下拉框的默认选项为第一项(例如 "特殊选项")或其他指定值
        for (int i = 0; i < FeedingOrderItems.Count; i++)
        {
            FeedingOrderItems[i].SelectedItem = new SetConfigWindow.Item { Id = /* 默认项的ID */, Name = /* 默认项的名称 */ }; // 设置默认项为第一项或其他指定项的值
            FeedingOrderItems[i].TextText = /* 默认项的文本值 */; // 设置默认项的文本值
            // 根据需要设置其他属性为默认值(例如 IsChecked 等)...
        }
    }
    

    请注意,这些修改需要你根据实际情况进行调整和测试。特别是联动选择逻辑部分可能需要根据你的具体需求进行适当调整。希望这些建议能够帮助你实现所需的功能。

    评论

报告相同问题?

问题事件

  • 创建了问题 10月19日

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀