1

Есть кнопка

<Button Width="100" Height="24" Header="ОК" x:Name="okButton"/>

Где-то в коде я меняю Width у этой кнопки.

okButton.Width = 200;

Как прописать анимацию плавного изменения размера? Т.е. как прицепить анимацию к полю Width, что бы не смотря откуда в коде я меняю его значение, срабатывала анимация?

2
  • Вам именно кнопка, или подойдёт UserControl?
    – VladD
    6 мая 2016 в 12:48
  • UserControl даже лучше
    – MaximK
    6 мая 2016 в 13:14

2 ответа 2

1

У меня получилось следующим образом: ловить изменение ширины UserControl'а, и запускать анимацию ширины контента.

При этом, правда, уменьшившаяся ширина UserControl'а «отрежет» медленно уменьшающиеся части контента, так что придётся отключить clipping вручную.

Контрол:

<UserControl x:Class="SlowWidthChanging.SlowResizingControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:SlowWidthChanging">
    <local:NoClipGrid x:Name="InnerPart" HorizontalAlignment="Center"
          Width="{Binding ActualWidth,
              RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}">
        <Button>Привет, мир!</Button>
    </local:NoClipGrid>
</UserControl>
public partial class SlowResizingControl : UserControl
{
    static DependencyPropertyDescriptor dpd =
        DependencyPropertyDescriptor.FromProperty(SlowResizingControl.WidthProperty,
                                                  typeof(SlowResizingControl));

    public SlowResizingControl()
    {
        InitializeComponent();
        Loaded += (o, args) =>
        {
            dpd.AddValueChanged(this, OnWidthChanged);
            OnWidthChanged(this, null);
        };
        // обязательно отписаться, чтобы избежать утечки памяти
        Unloaded += (o, args) =>
            dpd.RemoveValueChanged(this, OnWidthChanged);
    }

    void OnWidthChanged(object self, EventArgs args)
    {
        InnerPart.BeginAnimation(
            Grid.WidthProperty,
            new DoubleAnimation(
                toValue: this.Width,
                duration: new Duration(TimeSpan.FromSeconds(0.5)),
                fillBehavior: FillBehavior.Stop));
    }
}

Ну и вспомогательный класс (отсюда):

class NoClipGrid : Grid
{
    protected override Geometry GetLayoutClip(Size layoutSlotSize)
    {
        return null;
    }
}

Можно тестировать:

<Window x:Class="SlowWidthChanging.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SlowWidthChanging"
        Height="350" Width="525">
    <Grid x:Name="OuterContainer">
        <local:SlowResizingControl Height="50" Width="100" x:Name="SizeChangeTarget"/>
        <Button Width="150" Height="25" Content="Поменять ширину" Click="ChangeButtonSize"
                VerticalAlignment="Bottom" Margin="10"/>
    </Grid>
</Window>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    void ChangeButtonSize(object sender, RoutedEventArgs e)
    {
        double newWidth =
            (double.IsNaN(SizeChangeTarget.Width) || SizeChangeTarget.Width == 100) ?
            200 : 100;
        SizeChangeTarget.Width = newWidth;
    }
}
0

Здесь можно попробовать использовать триггеры событий. Например, что-нибудь наподобие такого:

<EventTrigger RoutedEvent="Button.Click">
    <EventTrigger.Actions>
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation  
                    Storyboard.TargetName="okButton"
                    Storyboard.TargetProperty="Width"
                    From="75"
                    To="200"
                    Duration="0:0:2"
                />
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger.Actions>
</EventTrigger>

Или прописать анимацию в виде "обычного" кода в каком-нибудь методе:

DoubleAnimation buttonAnimation = new DoubleAnimation();
//Начальное и конечное значение
buttonAnimation.From = okButton.ActualWidth;
buttonAnimation.To = 200;
//Продолжительность анимации
buttonAnimation.Duration = TimeSpan.FromSeconds(3);
//Запуск анимации
okButton.BeginAnimation(Button.WidthProperty, buttonAnimation);
1
  • Здесь используется событие самой кнопки Click; Думаю не подойдет
    – MaximK
    6 мая 2016 в 10:48

Ваш ответ

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

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