0

Я хочу сделать индикацию, где цвета задаются пользовательскими свойствами зависимости. Реализацию описываю в xaml и столкнулся проблемой. Реализация MainWindow.xaml

    <Window.Resources>
    <local:ConverterBrushToColor x:Key="BrushToColor"></local:ConverterBrushToColor>
    <Storyboard x:Key="Storyboard1" AutoReverse="True" RepeatBehavior="Forever">
        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(local:Animation.BrushColor0).(SolidColorBrush.Color)" Storyboard.TargetName="animation">
            <DiscreteColorKeyFrame KeyTime="0:0:1" Value="{Binding BrushColor1, Converter={StaticResource BrushToColor}, ElementName=animation}"/>
            <DiscreteColorKeyFrame KeyTime="0:0:2" Value="Green"/>
        </ColorAnimationUsingKeyFrames>
    </Storyboard>
</Window.Resources>
<Window.Triggers>
    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
        <BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
    </EventTrigger>
</Window.Triggers>
<Grid>
    <local:Animation x:Name="animation" 
                     HorizontalAlignment="Left"
                     Height="100" 
                     Margin="69.859,46.528,0,0" 
                     VerticalAlignment="Top" 
                     Width="100" 
                     BrushColor1="Red"/>
</Grid>

Реализация Animation.xaml

    <Grid>
    <Label Background="{Binding BrushColor0, ElementName=User}"
           BorderBrush="Black" 
           BorderThickness="2">

    </Label> 
</Grid>

Обертка Animation.xaml.cs

    public class ConverterColorToBrush : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (null == value)
            return null;
        if (value is Color)
        {
            Color color = (Color)value;
            return new SolidColorBrush(color);
        }
        Type type = value.GetType();
        throw new InvalidOperationException("Unsupported type [" + type.Name + "]");
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public class ConverterBrushToColor : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (null == value)
            return null;
        if (value is Brush)
        {
            Color color = (value as SolidColorBrush).Color;
            return color;
        }
        Type type = value.GetType();
        throw new InvalidOperationException("Unsupported type [" + type.Name + "]");
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public partial class Animation : UserControl
{
    public Animation() => InitializeComponent();

    public Color Color0
    {
        get { return (Color)GetValue(Color0Property); }
        set { SetValue(Color0Property, value); }
    }
    public static readonly DependencyProperty Color0Property =
        DependencyProperty.Register("Color0", typeof(Color), typeof(Animation), new PropertyMetadata(Color.FromRgb(125,125,125)));

    public Color Color1
    {
        get { return (Color)GetValue(Color1Property); }
        set { SetValue(Color1Property, value); }
    }
    public static readonly DependencyProperty Color1Property =
        DependencyProperty.Register("Color1", typeof(Color), typeof(Animation), new PropertyMetadata(Color.FromRgb(125, 125, 125)));

    public Brush BrushColor0
    {
        get { return (Brush)GetValue(BrushColor0Property); }
        set { SetValue(BrushColor0Property, value); }
    }
    public static readonly DependencyProperty BrushColor0Property =
        DependencyProperty.Register("BrushColor0", typeof(Brush), typeof(Animation), new PropertyMetadata(Brushes.Gray));

    public Brush BrushColor1
    {
        get { return (Brush)GetValue(BrushColor1Property); }
        set { SetValue(BrushColor1Property, value); }
    }
    public static readonly DependencyProperty BrushColor1Property =
        DependencyProperty.Register("BrushColor1", typeof(Brush), typeof(Animation), new PropertyMetadata(Brushes.Gray));
}

Я задаю цвет BrushColor1="Red" и хочу чтобы он через секунду поменял с BrushColor0="Gray" на BrushColor1="Red". Проблема в том, что я получаю анимацию с серого цвета на прозрачный. Почему мой BrushColor1="Red" игнорируется и вместо него красится прозрачный цвет? Вот этот чать кода работает не так как я хочу

<DiscreteColorKeyFrame KeyTime="0:0:1" Value="{Binding BrushColor1, Converter={StaticResource BrushToColor}, ElementName=animation}"/>

Из msdn, DiscreteColorKeyFrame.Value принимает только тип Color. Либо я неправильно конвертирую с Brush на Color, либо Binding в Value никаким образом не работает. Пробовал обратную конвертацию цвета сделать, когда Value передавал напрямую тип Brush и конвертировал в Color, но это тоже мне не помогло.

1 ответ 1

0

Вопрос решается так: Сперва нужно BrushColor0 определить не как Brush, а SolidColorBrush, а потом определить цвета в Resource таким образом:

 <SolidColorBrush Color="{Binding BrushColor0.Color, ElementName=User}" x:Key="BrushColor0"></SolidColorBrush>
 <SolidColorBrush Color="{Binding BrushColor1.Color, ElementName=User}" x:Key="BrushColor1"></SolidColorBrush>

а потом привязываться к DiscreteColorKeyFrame.Value

<DiscreteColorKeyFrame KeyTime="0:0:1" Value="{Binding Color, Source={StaticResource BrushColor0}}"/>
<DiscreteColorKeyFrame KeyTime="0:0:2" Value="{Binding Color, Source={StaticResource BrushColor1}}"/>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.