Скрыть элемент по умолчанию, затем оживить нажатие

Есть ли способ установить элемент в XAML для скрытия? Когда пользователи нажимают кнопку «Новая игра», я хочу, чтобы набор кнопок (возможно, в панели стека) отображался в окне просмотра, позволяя пользователю выбрать уровень сложности. Я попытался установить видимость на сбой, но когда я использую одну из встроенных анимаций Win8, таких как EntranceThemeTransition или PopIn, свернутый элемент не отображается. Изменение непрозрачности до 0, а затем попытка анимации с использованием одного из них имеет тот же эффект.

0
nl ja de
у вас еще есть код? Если да, то можете ли вы опубликовать то, что у вас есть до сих пор? Это может помочь добавить некоторый контекст.
добавлено автор Lizz, источник

1 ответы

Свойство Visibility работает независимо от Opacity. Вам нужно установить Visibility обратно на Visible перед запуском пользовательской анимации Opacity или встроенного FadeInThemeAnimation .

Вы можете использовать расширения WinRT XAML Toolkit для запуска простой анимации:

myElement.Visibility = Visibility.Visible;
myElement.FadeInCustom();

Класс методов расширения из XAML Toolkit:

using System;
using System.Threading.Tasks;
using WinRTXamlToolkit.AwaitableUI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Animation;

namespace WinRTXamlToolkit.Controls.Extensions
{
    /// 
    /// Extension methods and attached properties for UIElement class.
    /// 
    public static class UIElementAnimationExtensions
    {
        #region AttachedFadeStoryboard
        /// 
        /// AttachedFadeStoryboard Attached Dependency Property
        /// 
        public static readonly DependencyProperty AttachedFadeStoryboardProperty =
            DependencyProperty.RegisterAttached(
                "AttachedFadeStoryboard",
                typeof(Storyboard),
                typeof(UIElementAnimationExtensions),
                new PropertyMetadata(null, OnAttachedFadeStoryboardChanged));

        /// 
        /// Gets the AttachedFadeStoryboard property. This dependency property 
        /// indicates the currently running custom fade in/out storyboard.
        /// 
        private static Storyboard GetAttachedFadeStoryboard(DependencyObject d)
        {
            return (Storyboard)d.GetValue(AttachedFadeStoryboardProperty);
        }

        /// 
        /// Sets the AttachedFadeStoryboard property. This dependency property 
        /// indicates the currently running custom fade in/out storyboard.
        /// 
        private static void SetAttachedFadeStoryboard(DependencyObject d, Storyboard value)
        {
            d.SetValue(AttachedFadeStoryboardProperty, value);
        }

        /// 
        /// Handles changes to the AttachedFadeStoryboard property.
        /// 
        /// 
        /// The  on which
        /// the property has changed value.
        /// 
        /// 
        /// Event data that is issued by any event that
        /// tracks changes to the effective value of this property.
        /// 
        private static void OnAttachedFadeStoryboardChanged(
            DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Storyboard oldAttachedFadeStoryboard = (Storyboard)e.OldValue;
            Storyboard newAttachedFadeStoryboard = (Storyboard)d.GetValue(AttachedFadeStoryboardProperty);
        }
        #endregion

        #region FadeIn()
        /// 
        /// Fades the element in using the FadeInThemeAnimation.
        /// 
        /// 
        /// Opacity property of the element is not affected.
/// The duration of the visible animation itself is not affected by the duration parameter. It merely indicates how long the Storyboard will run.
/// If FadeOutThemeAnimation was not used on the element before - nothing will happen.
///
/// /// /// public static async Task FadeIn(this UIElement element, TimeSpan? duration = null) { ((FrameworkElement)element).Visibility = Visibility.Visible; var fadeInStoryboard = new Storyboard(); var fadeInAnimation = new FadeInThemeAnimation(); if (duration != null) { fadeInAnimation.Duration = duration.Value; } Storyboard.SetTarget(fadeInAnimation, element); fadeInStoryboard.Children.Add(fadeInAnimation); await fadeInStoryboard.BeginAsync(); } #endregion #region FadeOut() /// /// Fades the element out using the FadeOutThemeAnimation. /// /// /// Opacity property of the element is not affected.
/// The duration of the visible animation itself is not affected by the duration parameter. It merely indicates how long the Storyboard will run.
/// If FadeOutThemeAnimation was already run before and FadeInThemeAnimation was not run after that - nothing will happen.
///
/// /// /// public static async Task FadeOut(this UIElement element, TimeSpan? duration = null) { var fadeOutStoryboard = new Storyboard(); var fadeOutAnimation = new FadeOutThemeAnimation(); if (duration != null) { fadeOutAnimation.Duration = duration.Value; } Storyboard.SetTarget(fadeOutAnimation, element); fadeOutStoryboard.Children.Add(fadeOutAnimation); await fadeOutStoryboard.BeginAsync(); } #endregion #region FadeInCustom() /// /// Fades the element in using a custom DoubleAnimation of the Opacity property. /// /// /// /// /// public static async Task FadeInCustom(this UIElement element, TimeSpan? duration = null, EasingFunctionBase easingFunction = null, double targetOpacity = 1.0) { CleanUpPreviousFadeStoryboard(element); var fadeInStoryboard = new Storyboard(); var fadeInAnimation = new DoubleAnimation(); if (duration == null) duration = TimeSpan.FromSeconds(0.4); fadeInAnimation.Duration = duration.Value; fadeInAnimation.To = targetOpacity; fadeInAnimation.EasingFunction = easingFunction; Storyboard.SetTarget(fadeInAnimation, element); Storyboard.SetTargetProperty(fadeInAnimation, "Opacity"); fadeInStoryboard.Children.Add(fadeInAnimation); SetAttachedFadeStoryboard(element, fadeInStoryboard); await fadeInStoryboard.BeginAsync(); element.Opacity = targetOpacity; fadeInStoryboard.Stop(); } #endregion #region FadeOutCustom() /// /// Fades the element out using a custom DoubleAnimation of the Opacity property. /// /// /// /// /// public static async Task FadeOutCustom(this UIElement element, TimeSpan? duration = null, EasingFunctionBase easingFunction = null) { CleanUpPreviousFadeStoryboard(element); var fadeOutStoryboard = new Storyboard(); var fadeOutAnimation = new DoubleAnimation(); if (duration == null) duration = TimeSpan.FromSeconds(0.4); fadeOutAnimation.Duration = duration.Value; fadeOutAnimation.To = 0.0; fadeOutAnimation.EasingFunction = easingFunction; Storyboard.SetTarget(fadeOutAnimation, element); Storyboard.SetTargetProperty(fadeOutAnimation, "Opacity"); fadeOutStoryboard.Children.Add(fadeOutAnimation); SetAttachedFadeStoryboard(element, fadeOutStoryboard); await fadeOutStoryboard.BeginAsync(); element.Opacity = 0.0; fadeOutStoryboard.Stop(); } #endregion #region CleanUpPreviousFadeStoryboard() public static void CleanUpPreviousFadeStoryboard(this UIElement element) { var attachedFadeStoryboard = GetAttachedFadeStoryboard(element); if (attachedFadeStoryboard != null) { attachedFadeStoryboard.Stop(); } } #endregion } }
0
добавлено
Microsoft Stack Jobs
Microsoft Stack Jobs
1 788 участник(ов)

Work & freelance only Microsoft Stack. Feed https://t.me/Microsoftstackjobsfeed Чат про F#: @Fsharp_chat Чат про C#: @CSharpChat Чат про Xamarin: @xamarin_russia Чат общения:@dotnettalks

Про Windows
Про Windows
941 участник(ов)

Microsoft Windows и всё, что с этим связано. Список интересных групп и каналов: https://github.com/goq/telegram-list

Microsoft Developer Community Chat
Microsoft Developer Community Chat
584 участник(ов)

Чат для разработчиков и системных администраторов Microsoft Developer Community. __________ Новостной канал: @msdevru __________ Баним за: оскорбления, мат, рекламу, флуд, флейм, спам, NSFW контент, а также большое количество оффтоп тем. @banofbot