代码之家  ›  专栏  ›  技术社区  ›  eye_am_groot

阻止两个组合框选择同一项

  •  0
  • eye_am_groot  · 技术社区  · 7 年前

    我正在寻找一种方法来防止两个(或更多) ComboBoxes 从有相同的 SelectedItem . 我有多个 组合框 都是一样的 ItemsSource

    <ComboBox Width="50" ItemsSource="{Binding Keys}" SelectedItem="{Binding LoadedBackgroundKey, NotifyOnValidationError=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    <ComboBox Width="50" ItemsSource="{Binding Keys}" SelectedItem="{Binding LoadedForegroundKey, NotifyOnValidationError=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    <ComboBox Width="50" ItemsSource="{Binding Keys}" SelectedItem="{Binding IncreaseSizeKey, NotifyOnValidationError=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    

    在ViewModel中:

    public Key LoadedBackgroundKey { get; set; }
    public Key LoadedForegroundKey { get; set; }
    public Key IncreaseSizeKey { get; set; }
    private ObservableCollection<Key> _availableKeys;
    public IEnumerable<Key> Keys => _availableKeys;
    

    _availableKeys 用适当的键填充( A , B 等)。我希望能够防止在多个组合框中选择同一个键,或者(至少)在多个框中选择同一个键时给出一个错误。

    This question 可能是类似的,我正在寻找的,但我不确定它相当的工作(也许我只是不理解它正确)。它也只解释了两种情况 Comboboxes . 是一个 ValidationRule 最好的方法是什么?如果是这样,我将如何实现这个,检查所有 ? 还是有更简单的方法?

    1 回复  |  直到 7 年前
        1
  •  2
  •   mm8    7 年前

    你可以实现 INotifyDataErrorInfo 接口,并在设置任何相关属性时执行验证逻辑,例如:

    public class ViewModel : INotifyDataErrorInfo
    {
        public Key LoadedBackgroundKey
        {
            get => keys[0];
            set
            {
                Validate(nameof(LoadedBackgroundKey), value);
                keys[0] = value;
            }
        }
    
        public Key LoadedForegroundKey
        {
            get => keys[1];
            set
            {
                Validate(nameof(LoadedForegroundKey), value);
                keys[1] = value;
            }
        }
    
        public Key IncreaseSizeKey
        {
            get => keys[2];
            set
            {
                Validate(nameof(IncreaseSizeKey), value);
                keys[2] = value;
            }
        }
    
        public IEnumerable<Key> Keys { get; } = new ObservableCollection<Key> { ... };
    
        private void Validate(string propertyName, Key value)
        {
            if (keys.Contains(value))
                _validationErrors[propertyName] = "duplicate...";
            else
                _validationErrors.Remove(propertyName);
    
            ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
        }
    
        private readonly Key[] keys = new Key[3];
        private readonly Dictionary<string, string> _validationErrors = new Dictionary<string, string>();
        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
        public bool HasErrors => _validationErrors.Count > 0;
        public IEnumerable GetErrors(string propertyName) =>
            _validationErrors.TryGetValue(propertyName, out string error) ? new string[1] { error } : null;
    }