WPF Привязать количество элементов к цвету текста TextBlock - PullRequest
0 голосов
/ 10 февраля 2011

У меня есть класс конвертера, который привязывает Count of TagName к FontSize, как показано ниже.Сейчас я пытаюсь добиться того, чтобы каждые 3 шага FontSize связывались с другим цветом.Кто-нибудь может помочь?

Конвертер

public class CountToFontSizeConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        const int minFontSize = 6;
        const int maxFontSize = 38;
        const int increment = 3;
        int count = (int)value;

        if ((minFontSize + count + increment) < maxFontSize)
        {
            return minFontSize + count + increment;            
        }
        return maxFontSize;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
    #endregion
}

Фрагмент XAML

<DataTemplate x:Key="TagsTemplate">
        <WrapPanel>
            <TextBlock Text="{Binding Name, Mode=Default}" 
                       TextWrapping="Wrap" 
                       FontSize="{Binding ItemCount, Converter={StaticResource CountToFontSizeConverter}, Mode=Default}" 
                       Foreground="#FF0D0AF7" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </WrapPanel>
    </DataTemplate>

Новый шаблон данных

<DataTemplate x:Key="TagsTemplate">
        <WrapPanel>
            <TextBlock Text="{Binding Name, Mode=Default}" 
                       TextWrapping="Wrap" 
                       FontSize="{Binding ItemCount, Converter={StaticResource CountToFontSizeConverter}, Mode=Default}" 
                       Foreground="{Binding count, Converter={StaticResource CountToBrushConverter}}"/>
        </WrapPanel>
    </DataTemplate>

Ответы [ 2 ]

1 голос
/ 10 февраля 2011

Низкий счет = черный;
Большой счет = синий;

public class CountToBrushConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        const int cap = 32;
        int count = (int)value;
        count -= count % 3; // Modulo division to make sure
                            // that the value only changes
                            // every 3 steps

        double res = count <= cap ? count : cap; // Check if maximum
                                                 // has been reached
        res /= cap; // Normalize value to be between 0 and 1
        Color colour = new Color();
        colour.ScA = 1; // Set the alpha to full visibility
        colour.ScB = (float)res; // Set the blue channel to our value

        return new SolidColorBrush(colour);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
    #endregion
}
0 голосов
/ 10 февраля 2011

Вы можете создать другой конвертер, который будет преобразовывать текущий размер шрифта в кисть.Конвертер может выглядеть примерно так:

public class FontSizeToBrushConverter : IValueConverter {
    public static readonly double Increment = 3;
    public static readonly double MinFontSize = 6;
    public static readonly double MaxFontSize = 32;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        if (value == null || value == DependencyProperty.UnsetValue) {
            return DependencyProperty.UnsetValue;
        }

        var fontSize = (double) value;

        double incrementsCount = MaxFontSize / Increment;

        var defaultColor = new SolidColorBrush(Colors.Black);

        for (int incrementIndex = 0; incrementIndex < incrementsCount; incrementIndex++) {
            if (fontSize == MinFontSize + Increment * incrementIndex) {
                switch (incrementIndex) {
                    case 0:
                        return new SolidColorBrush(Colors.Red);
                    case 1:
                        return new SolidColorBrush(Colors.Green);
                    case 2:
                        return new SolidColorBrush(Colors.Blue);
                    default:
                        return defaultColor; // Default color
                }
            }
        }

        return defaultColor; // Default color
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        throw new NotImplementedException();
    }
}

Возможно, вы захотите переместить константы, определенные в верхней части этого класса, куда-нибудь, чтобы разделить их между вашими двумя конвертерами.

Используя этот конвертер, выXAML будет выглядеть так:

<DataTemplate x:Key="TagsTemplate">
    <WrapPanel>
        <TextBlock Text="{Binding Name, Mode=Default}" 
               TextWrapping="Wrap" 
               FontSize="{Binding ItemCount, Converter={StaticResource CountToFontSizeConverter}, Mode=Default}" 
               Foreground="{Binding FontSize, RelativeSource={RelativeSource Self}, Converter={StaticResource FontSizeToBrushConverter}}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </WrapPanel>
</DataTemplate>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...