Гость
Форумы / WPF, Silverlight [игнор отключен] [закрыт для гостей] / Шаблон для лейбла с анимацией / 7 сообщений из 7, страница 1 из 1
26.07.2017, 10:58
    #39495099
sposad
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Шаблон для лейбла с анимацией
Вот продолжаю ковырять WPF. Теперь впёрло сделать надпись с анимированным фоном. Просто сделать один анимированный лейбл получается, а вот через шаблон - нет. Непонятно, что указывать в ColorAnimation Storyboard.TargetName.

шаблон
Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
<ControlTemplate x:Key="RoundLabel" TargetType="{x:Type Label}">            
            <Border x:Name="border" CornerRadius="10" BorderThickness="3" BorderBrush="{TemplateBinding Property=BorderBrush}" Background="{TemplateBinding Property=Background}" 
                    TextBlock.FontSize="12" TextBlock.FontStyle="Italic">
                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
        						Margin="{TemplateBinding Padding}" 
        						VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
        						Content="{TemplateBinding Content}" 
        						ContentTemplate="{TemplateBinding ContentTemplate}"/>
            </Border>
               <ControlTemplate.Triggers>
                <EventTrigger RoutedEvent="Loaded">
                    <BeginStoryboard>

                           <ColorAnimation Storyboard.TargetName="???"
                              Storyboard.TargetProperty = "(Label.Background).(LinearGradientBrush.GradientStops)[0].(GradientStop.Color)"
                              From="Black" To="Red" Duration="0:0:5"/>

                       </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>



сам лейбл

Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
<Label x:Name="lbCallb" Template="{StaticResource RoundLabel}"  Content= "Всего на текущий момент" HorizontalAlignment="Left" Height="31" Margin="10,34,0,0" VerticalAlignment="Top" Width="207" BorderBrush="Black">
                <Label.Background>
                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black" Offset="0"/>
                        <GradientStop Color="Red" Offset="1"/>
                    </LinearGradientBrush>
                </Label.Background>
                <!--<Label.Triggers>
                    <EventTrigger RoutedEvent="Loaded">
                        <BeginStoryboard>
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetName="lbCallb" Storyboard.TargetProperty="(Label.Background).(LinearGradientBrush.GradientStops)[0].(GradientStop.Color)" From="Black" To="Red" AutoReverse="True"
                                 BeginTime="0:0:0" Duration="0:0:2" RepeatBehavior="Forever">                                    
                                </ColorAnimation>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Label.Triggers>-->
            </Label>



Подскажите плз...
...
Рейтинг: 0 / 0
26.07.2017, 11:44
    #39495132
Roman Mejtes
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Шаблон для лейбла с анимацией
sposad,

Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
<Window x:Class="WpfApp8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ControlTemplate x:Key="RoundLabel" TargetType="{x:Type Label}">
            <Border x:Name="border" CornerRadius="10" 
                    BorderThickness="3" 
                    BorderBrush="{TemplateBinding BorderBrush}" 
                    Background="{TemplateBinding Background}" 
                    TextBlock.FontSize="12" 
                    TextBlock.FontStyle="Italic">
                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
        						Margin="{TemplateBinding Padding}" 
        						VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
        						Content="{TemplateBinding Content}" 
        						ContentTemplate="{TemplateBinding ContentTemplate}"/>
            </Border>
            <ControlTemplate.Triggers>
                <EventTrigger RoutedEvent="Loaded">
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation Storyboard.TargetName="border"
                                        Storyboard.TargetProperty="Background.(LinearGradientBrush.GradientStops)[0].(GradientStop.Color)"
                                        From="Black" To="Red" Duration="0:0:5" />

                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
        <Style TargetType="{x:Type Label}">
            <Setter Property="Template" Value="{StaticResource RoundLabel}"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Label>
            <Label.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="Red" Offset="1"/>
                </LinearGradientBrush>
            </Label.Background>
        </Label>
    </Grid>
</Window>
...
Рейтинг: 0 / 0
26.07.2017, 12:05
    #39495160
sposad
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Шаблон для лейбла с анимацией
Roman Mejtes,

СПАСИБО! Только непонятно, почему все-таки border...
...
Рейтинг: 0 / 0
26.07.2017, 12:07
    #39495165
Roman Mejtes
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Шаблон для лейбла с анимацией
sposad,

потому, что вы назвали Border как "border"
<Border x:Name="border" в 1 строке шаблона
...
Рейтинг: 0 / 0
26.07.2017, 12:15
    #39495182
sposad
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Шаблон для лейбла с анимацией
Roman Mejtessposad,

потому, что вы назвали Border как "border"
<Border x:Name="border" в 1 строке шаблонаСпасибо ещё раз, кажется я не сразу понял к чему именно должно относиться это имя
...
Рейтинг: 0 / 0
26.07.2017, 12:17
    #39495184
Roman Mejtes
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Шаблон для лейбла с анимацией
+ такой подход неправильный. У вас анимация цвета задана в шаблоне, а сам цвет фона задан локально у объекта. По сути, в разных местах. Это неправильный подход. А если цвет фона не задать, то анимация вообщен е сработает и даже может исключение вылететь.
Более правильно будет, перенести сам цвет и анимацию в стиль, вот так:
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
<Window x:Class="WpfApp8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="{x:Type Label}">
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black" Offset="0"/>
                        <GradientStop Color="Red" Offset="1"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <EventTrigger RoutedEvent="Loaded">
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation Storyboard.TargetProperty="Background.(LinearGradientBrush.GradientStops)[0].(GradientStop.Color)"
                                            From="Black" To="Red" 
                                            Duration="0:0:5" />

                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <Label>Example</Label>
    </Grid>
</Window>


как видите, тут вообще нет ни каких шаблонов, инициализация цвета фона находится там же, где и его анимация, а если задаю ключ стиля, можно быстро задать анимацию для Label'а задав нужный стиль.
нужно с умом использовать анимацию там, где она должна быть, в данном случае в шаблоне делать анимаю нет нужды.
И еще одно замечание. Событие Loaded работает совсем не так, как в WinForms, оно может сработать далеко не 1 раз. Оно сработает, если пользователь сменить системные насройки Themes системы или если удалить и добавить объект в визуальное дерево, и в некоторых других случаях.
Если объект находится в виртуализированном списке, то при каждом его появление в области видимости, будет срабатывать анимация.
...
Рейтинг: 0 / 0
26.07.2017, 12:25
    #39495196
sposad
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Шаблон для лейбла с анимацией
Roman Mejtes,

Очень признателен Вам! Не всегда в мануалах удаётся найти именно нужное сейчас
...
Рейтинг: 0 / 0
Форумы / WPF, Silverlight [игнор отключен] [закрыт для гостей] / Шаблон для лейбла с анимацией / 7 сообщений из 7, страница 1 из 1
Целевая тема:
Создать новую тему:
Автор:
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]