2

I have a editable combobox in WPF (IsEditable=True). I would also like to ensure that the values which the user enters are in the list only. I don't want user to add their own values to the combo. I cannot make IsReadonly=true as that will not allow users to type. So is validation the only option in SelectionChange event? or is there a better way to do the same?

Thanks Shankara Narayanan.

4

2 回答 2

1

我这样做是为了让用户通过将测试变为红色来告知他们的输入无效。但是您可以使用类似的方法来做其他事情。

XAML:

<Window x:Class="local.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:EditableComboBox="clr-namespace:EditableComboBox"
    Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <EditableComboBox:ComboBoxViewModel />
    </Window.DataContext>
    <StackPanel>
        <ComboBox IsEditable="True" Foreground="{Binding ComboBoxColor, Mode=TwoWay}" Text="{Binding ComboBoxText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>
</Window>

编码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Media;

namespace EditableComboBox
{
    class ComboBoxViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string m_ComboBoxText;
        public string ComboBoxText
        {
            get { return m_ComboBoxText; }
            set
            {
                m_ComboBoxText = value;
                OnPropertyChanged("ComboBoxText");
                ValidateText();
            }
        }

        private void ValidateText()
        {
            if (ComboBoxText.Length % 2 == 0)
                ComboBoxColor = Brushes.Black;
            else
                ComboBoxColor = Brushes.Red;
        }

        private Brush m_ComboBoxColor;
        public Brush ComboBoxColor
        {
            get { return m_ComboBoxColor; }
            set
            {
                m_ComboBoxColor = value;
                OnPropertyChanged("ComboBoxColor");
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
于 2012-11-06T23:30:29.990 回答
0

好吧..这就是我所做的

List<dynamic> list = cmbToAcc.ItemsSource as List<dynamic>;
        var result = from s in list
                     where (string)s.Name == (string)cmbToAcc.Text
                     select s;

        if (result.Count() <= 0)
        {
            Helper.Inform("Please select a valid value.");
            cmbToAcc.SelectedIndex = 0;
            cmbToAcc.Focus();
        }

这是在 LostFocus 事件中。

我不确定这是否是最好的方法..但可以达到目的

谢谢

尚卡拉·纳拉亚南

于 2012-11-06T23:55:24.740 回答