在我的应用程序中,我有一个网格,其可见性绑定到视图模型中的属性。
我想要做的是当视图模型中的visibility属性发生变化时,网格根据可见性值淡入或淡出:Visible / Collapsed。
我怎样才能做到这一点?
答案 0 :(得分:4)
受到“HDW Production”答案的启发,这里是Windows Store和Windows Phone Store应用程序的代码:
public class FadingVisibilityGrid : Grid
{
public static readonly DependencyProperty DeferredVisibilityProperty = DependencyProperty.Register(
"DeferredVisibility", typeof (Visibility), typeof (FadingVisibilityGrid), new PropertyMetadata(default(Visibility), DeferredVisibilityChanged));
private static void DeferredVisibilityChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var newVisibility = (Visibility)e.NewValue;
var grid = (FadingVisibilityGrid)sender;
var animation = new DoubleAnimation
{
Duration = new Duration(TimeSpan.FromMilliseconds(200))
};
Storyboard.SetTarget(animation, grid);
Storyboard.SetTargetProperty(animation, "Grid.Opacity");
grid.FadeStoryBoard.Stop();
grid.FadeStoryBoard = new Storyboard();
grid.FadeStoryBoard.Children.Add(animation);
if (newVisibility == Visibility.Visible)
{
animation.From = 0;
animation.To = 1;
grid.Visibility = Visibility.Visible;
grid.FadeStoryBoard.Begin();
}
else
{
animation.From = 1;
animation.To = 0;
grid.FadeStoryBoard.Completed += (o, o1) =>
{
grid.Visibility = newVisibility;
};
grid.FadeStoryBoard.Begin();
}
}
public Visibility DeferredVisibility
{
get { return (Visibility) GetValue(DeferredVisibilityProperty); }
set { SetValue(DeferredVisibilityProperty, value); }
}
private Storyboard _fadeStoryBoard = new Storyboard();
public Storyboard FadeStoryBoard
{
get { return _fadeStoryBoard; }
set { _fadeStoryBoard = value; }
}
}
答案 1 :(得分:0)
您需要一个新的DependencyProperty,可以通过继承Grid并添加一个或创建附加属性。我们称之为DeferredVisibility,让它为Visibility类型。
当DeferredVisibility更改为Visible时,将Visibility设置为Visible,并将不透明度从0设置为1。
当DeferredVisibility更改为Collapsed时,将不透明度从1设置为0,然后将可见性设置为折叠。