您可以使用IValueConverter。这需要相当多的代码,但如果您想要走
MVVM路径或按照WPF方式进行操作,则这是首选方法。
首先,创建一个实现IValueConverter的类。
public class IllegalCharactersToUnderscoreConverter
: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var stringValue = value as String;
if(stringValue == null)
return value;
return RemoveIllegalCharacters(stringValue);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
}
导入包含您的ValueConverter的命名空间
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
在Window.Resources中创建您的转换器的实例。
<Window.Resources>
<local:IllegalCharactersToUnderscoreConverter x:Key="IllegalCharactersToUnderscore" />
</Window.Resources>
在绑定表达式中使用转换器。UpdateSourceTrigger=PropertyChanged是必需的,以便在您输入时将文本转换。
<TextBox Text="{Binding MyText,
Converter={StaticResource IllegalCharactersToUnderscore},
UpdateSourceTrigger=PropertyChanged}"/>