我有一个文本框供用户输入 6 个字符的十六进制颜色值、一个验证器和一个附加到它的转换器。到这里为止,一切正常。但我想将文本框的Background
颜色绑定到文本框(ElementName
s Background
& Foreground
)指定的颜色,它似乎不起作用。
当我调试/单步执行代码时,该值似乎总是""
XAML
<TextBox x:Name="Background" Canvas.Left="328" Canvas.Top="33" Height="23" Width="60">
<TextBox.Text>
<Binding Path="Background">
<Binding.ValidationRules>
<validators:ColorValidator Property="Background" />
</Binding.ValidationRules>
<Binding.Converter>
<converters:ColorConverter />
</Binding.Converter>
</Binding>
</TextBox.Text>
</TextBox>
<TextBlock Canvas.Left="403" Canvas.Top="12" Text="Foreground" />
<TextBox x:Name="Foreground" Canvas.Left="403" Canvas.Top="33" Height="23" Width="60">
<TextBox.Text>
<Binding Path="Foreground">
<Binding.ValidationRules>
<validators:ColorValidator Property="Foreground" />
</Binding.ValidationRules>
<Binding.Converter>
<converters:ColorConverter />
</Binding.Converter>
</Binding>
</TextBox.Text>
</TextBox>
<!-- in this example I used the converter used in the TextBox & another converter that converts a string to color -->
<TextBox ...
Background="{Binding ElementName=Background, Path=Text, Converter={StaticResource colorConverter}}"
Foreground="{Binding ElementName=Foreground, Path=Text, Converter={StaticResource stringToColorConverter}}" />
转换器
class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
string entry = ((Color)value).ToString();
return entry.Substring(3);
} catch (Exception) {
return Binding.DoNothing;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string entry = (string)value;
Validators.ColorValidator validator = new Validators.ColorValidator();
if (!validator.Validate(entry, System.Globalization.CultureInfo.CurrentCulture).IsValid) {
return Binding.DoNothing;
}
return (Color)System.Windows.Media.ColorConverter.ConvertFromString("#FF" + entry);
}
}
class StringToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string entry = (string)value;
Validators.ColorValidator validator = new Validators.ColorValidator();
if (!validator.Validate(entry, System.Globalization.CultureInfo.CurrentCulture).IsValid)
{
return Binding.DoNothing;
}
return (Color)System.Windows.Media.ColorConverter.ConvertFromString("#FF" + entry);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}