在这种情况下使用转换器是个好主意,但您不需要多个转换器。相反,我们定义了一个具有多个参数的转换器:
public class TextBoxValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || string.IsNullOrEmpty(parameter as string))
throw new ArgumentException("Invalid arguments specified for the converter.");
switch (parameter.ToString())
{
case "labelText":
return string.Format("There are {0} characters in the TextBox.", ((string)value).Count());
case "backgroundColor":
return ((string)value).Count() > 20 ? Brushes.SkyBlue : Brushes.White;
default:
throw new ArgumentException("Invalid paramater specified for the converter.");
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后在您的 XAML 中,您可以像这样使用它:
<TextBox Name="textBox" Background="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource converter}, ConverterParameter=backgroundColor}"/>
<Label Content="{Binding ElementName=textBox, Path=Text, Converter={StaticResource converter}, ConverterParameter=labelText}"/>