1
我有一個文本框供用戶輸入6個字符的十六進制顏色值,一個驗證器&轉換器附加到它。到此爲止,一切正常。但我想將文本框的顏色與文本框中指定的顏色綁定(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();
}
}
我不確定,因此一個評論,但也許問題是,TextBox.Background等都需要一個畫筆,而不是一個顏色。 – Jens 2010-11-03 13:19:32
一個更好的標題肯定會有助於收集適當的關注。 – dhill 2010-11-03 13:19:50
正如Jens所說,嘗試轉換爲Brush而不是Color – snurre 2010-11-03 13:23:43