Как привязать к цвету фона TextBox - PullRequest
1 голос
/ 03 ноября 2010

У меня есть текстовое поле, в котором пользователь может ввести 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();
    }
}

1 Ответ

0 голосов
/ 05 декабря 2010

Все говорят, что вам нужна кисть, а не цвет.

Решение: Создайте еще один конвертер, который возвращает SolidColorBrush, и вы получите золотой.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...