温馨提示:本站为童趣票务官方授权演出订票中心,请放心购买。
你现在的位置:首页 > 演出资讯  > 儿童亲子

Grid 动态横向动画显示 Item

发布时间:2025-08-12 09:40:46  浏览量:3

Grid 动态横向动画显示 Item

控件名:AnimationGrid

作 者:WPFDevelopersOrg - 驚鏵

原文链接[1]:https://GitHub.com/WPFDevelopersOrg/WPFDevelopers

码云链接[2]:https://gitee.com/WPFDevelopersOrg/WPFDevelopers

框架支持 .NET4 至 .NET8;Visual Studio 2022;欢迎各位开发者下载并体验。如果在使用过程中遇到任何问题,欢迎随时向我们反馈[3]。AnimationGrid控件通过动画效果动态展示和隐藏数据项。默认控件会显示一个内容项。当添加第二个内容时,第一个内容的宽度会自动变小,第二个内容则从右侧滑入并展示。ItemsSource: 绑定到控件的数据集合,当ItemsSource变化时,会触发OnItemsSourceChanged方法来重新初始化项。每个数据项通过ItemTemplate加载并渲染为FrameworkElement。ItemTemplate: 数据项模板。InitializeItems:方法清空当前控件中的Items,重新添加新的内容,每个Item的宽度设置为0,并且Visibility设置为Collapsed,初始不可见,第一个Item设置立即显示,并调用UpdateLayoutAnimated来更新布局。ShowItem:切换Item数据项的显示状态。如果数据项未在VisibleItems中,就添加到集合中并显示。如果它已经在VisibleItems中,则移除并隐藏。AnimateWidth:当Item发生变化时,控件会通过DoubleAnimation动画来修改Item的Width动画时长设置300毫秒。using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespaceWPFDevelopers.Controls
{
publicclassAnimationGrid : Grid
{
privatereadonlyobject _syncLock = newobject;

publicstaticreadonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register(nameof(ItemsSource), typeof(IEnumerable), typeof(AnimationGrid),
new PropertyMetadata(null, OnItemsSourceChanged));

publicstaticreadonly DependencyProperty ItemTemplateProperty =
DependencyProperty.Register(nameof(ItemTemplate), typeof(DataTemplate), typeof(AnimationGrid),
new PropertyMetadata(null));

privatereadonly Dictionaryobject, FrameworkElement> _itemMap = new Dictionaryobject, FrameworkElement>;
privatereadonly HashSetobject> _visibleItems = new HashSetobject>;

public IEnumerable ItemsSource
{
get => (IEnumerable)GetValue(ItemsSourceProperty);
set => SetValue(ItemsSourceProperty, value);
}

public DataTemplate ItemTemplate
{
get => (DataTemplate)GetValue(ItemTemplateProperty);
set => SetValue(ItemTemplateProperty, value);
}
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is AnimationGrid panel)
{
panel.InitializeItems;
}
}

private void InitializeItems
{
Children.Clear;
ColumnDefinitions.Clear;
_itemMap.Clear;
_visibleItems.Clear;

if (ItemsSource == null || ItemTemplate == null) return;

foreach (var item in ItemsSource)
{
var content = (FrameworkElement)ItemTemplate.LoadContent;
content.DataContext = item;
content.Visibility = Visibility.Collapsed;
content.Width = 0;
_itemMap[item] = content;
Children.Add(content);
}
if (_itemMap.Count > 0)
{
var first = _itemMap.First;
_visibleItems.Add(first.Key);
first.Value.Visibility = Visibility.Visible;
UpdateLayoutAnimated;
}
}

public void ShowItem(object item)
{
lock (_syncLock)
{
if (!_itemMap.ContainsKey(item))
return;
if (_visibleItems.Contains(item))
_visibleItems.Remove(item);
else
_visibleItems.Add(item);
_itemMap[item].Visibility = Visibility.Visible;

}
}

private void UpdateLayoutAnimated
{

var visibleCount = Math.Max(1, _visibleItems.Count);
var width = this.Width;
var targetWidth = ActualWidth / visibleCount;
int index = 0;
foreach (var item in _itemMap.Keys)
{
ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
var element = _itemMap[item];
SetColumn(element, index);

{
AnimateWidth(element, targetWidth);
}
else
{
AnimateWidth(element, 0, => element.Visibility = Visibility.Collapsed);
}
index++;
}
}

private void AnimateWidth(FrameworkElement element, double targetWidth, Action completed = null)
{
var anim = new DoubleAnimation
{
To = targetWidth,
Duration = TimeSpan.FromMilliseconds(300),
EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
};
if (completed != null)
{
anim.Completed += delegate { completed; };
}
element.BeginAnimation(WidthProperty, anim);
}

protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
if (_visibleItems.Count > 0)
{

}
}
}
}

UserControl
x:Class="WPFDevelopers.Samples.ExampleViews.AnimationGridExample"
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"
xmlns:wd="https://github.com/WPFDevelopersOrg/WPFDevelopers"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">
UserControl.Resources>
DataTemplate x:Key="GridItemTemplate">
Button Content="{Binding Content}" />
DataTemplate>
Style TargetType="ToggleButton">
Setter Property="Width" Value="30" />
Setter Property="Height" Value="20" />
Setter Property="Template">
Setter.Value>
ControlTemplate TargetType="ToggleButton">
Border
x:Name="border"
Background="Transparent"
BorderBrush="Transparent"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="4">
wd:PathIcon x:Name="pathIcon" Data="{Binding Data}" />
Border>
ControlTemplate.Triggers>
Trigger Property="IsChecked" Value="True">
Setter Property="Foreground" Value="{DynamicResource WD.PrimaryBrush}" />
Trigger>
Trigger Property="IsMouseOver" Value="True">
Setter TargetName="border" Property="BorderBrush" Value="{DynamicResource WD.PrimaryBrush}" />
Trigger>

ControlTemplate>
Setter.Value>
Setter>
Style>
DataTemplate x:Key="ToggleItemTemplate">
ToggleButton
Command="{Binding IsSelectedCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
CommandParameter="{Binding .}"
IsChecked="{Binding IsSelected}"
Tag="{Binding Content}" />
DataTemplate>

Grid>
wd:AnimationGrid
x:Name="MyPanel"
ItemTemplate="{StaticResource GridItemTemplate}"
ItemsSource="{Binding GridItems, RelativeSource={RelativeSource AncestorType=UserControl}}" />
Border
Margin="0,10"
Padding="6"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Background="{DynamicResource WD.BackgroundBrush}"
CornerRadius="3"
Effect="{StaticResource WD.PrimaryShadowDepth}">
ItemsControl ItemTemplate="{StaticResource ToggleItemTemplate}" ItemsSource="{Binding GridItems, RelativeSource={RelativeSource AncestorType=UserControl}}">
ItemsControl.ItemsPanel>
ItemsPanelTemplate>
StackPanel Orientation="Horizontal" />
ItemsPanelTemplate>

ItemsControl>
Border>
Grid>
UserControl>
public partialclassAnimationGridExample : UserControl
{
public ObservableCollection
{
get { return (ObservableCollection
set { SetValue(GridItemsProperty, value); }
}

publicstaticreadonly DependencyProperty GridItemsProperty =
DependencyProperty.Register("GridItems", typeof(ObservableCollection
public AnimationGridExample
{
InitializeComponent;
Loaded += OnAnimatedGridExample_Loaded;
}

private void OnAnimatedGridExample_Loaded(object sender, RoutedEventArgs e)
{
var list = new List
list.Add(new GridItem { Content = "Single", Data = "M0.5,0.5 L60.5,0.5 L60.5,43.26 L0.5,43.26 z", IsSelected = true });
list.Add(new GridItem { Content = "Dual", Data = "M0,0 L61,0 L61,43.760002 L0,43.760002 z M25.5,0 L35.5,0 L35.5,43.760002 L25.5,43.760002 z" });
list.Add(new GridItem { Content = "Three", Data = "M0,0 L61,0 L61,43.760002 L0,43.760002 z M17,0.5 L22,0.5 L22,43.260002 L17,43.260002 z M39,0.5 L44,0.5 L44,43.260002 L39,43.260002 z" });
GridItems = new ObservableCollection
}

public ICommand IsSelectedCommand => new RelayCommand(param =>
{
if (param == null) return;
var item = (GridItem)param;
if (item == null) return;
MyPanel.ShowItem(item);
});

}
publicclassGridItem : ViewModelBase
{
publicstring Content { get; set; }
publicstring Data { get; set; }

privatebool _isSelected;
publicbool IsSelected
{
get => _isSelected;
set { _isSelected = value; NotifyPropertyChange("IsSelected"); }
}
}

GitHub 源码地址[4]

Gitee 源码地址[5]

[1]

[2]

[3]

反馈:

[4]

GitHub 源码地址:

[5]

Gitee 源码地址: