我这样做是为了让用户通过将测试变为红色来告知他们的输入无效。但是您可以使用类似的方法来做其他事情。
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));
}
}
}