当前位置:首页 > 技术知识 > 正文内容

Grid 动态横向动画显示 Item(datagrid横向滚动条)

Grid 动态横向动画显示 Item

控件名:AnimationGrid

作 者:WPFDevelopersOrg - 驚鏵

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

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

  • 框架支持 .NET4 至 .NET8
  • Visual Studio 2022 ;

欢迎各位开发者下载并体验。如果在使用过程中遇到任何问题,欢迎随时向我们反馈[3]

控件功能
  • AnimationGrid 控件通过动画效果动态展示和隐藏数据项。默认控件会显示一个内容项。当添加第二个内容时,第一个内容的宽度会自动变小,第二个内容则从右侧滑入并展示。

1. 新增 AnimationGrid.cs
  • ItemsSource : 绑定到控件的数据集合,当 ItemsSource 变化时,会触发 OnItemsSourceChanged 方法来重新初始化项。每个数据项通过 ItemTemplate 加载并渲染为 FrameworkElement
  • ItemTemplate : 数据项模板。
  • InitializeItems :方法清空当前控件中的 Items ,重新添加新的内容,每个 Item 的宽度设置为 0 ,并且 Visibility 设置为 Collapsed ,初始不可见,第一个 Item 设置立即显示,并调用 UpdateLayoutAnimated 来更新布局。
  • ShowItem :切换 Item 数据项的显示状态。如果数据项未在 VisibleItems 中,就添加到集合中并显示。如果它已经在 VisibleItems 中,则移除并隐藏。
  • AnimateWidth :当 Item 发生变化时,控件会通过 DoubleAnimation 动画来修改 ItemWidth 动画时长设置 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;
UpdateLayoutAnimated();
}
}

private void UpdateLayoutAnimated()
{
ColumnDefinitions.Clear();
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);
if (_visibleItems.Contains(item))
{
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)
{
UpdateLayoutAnimated();
}
}
}
}

2. 新增 AnimationGridExample.xaml
  • GridItemTemplate :新增数据模板;
  • 新增 ToggleButton 样式;
  • IsSelectedCommand :绑定选择命令;
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.Triggers>
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>
UserControl.Resources>
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.ItemsPanel>
ItemsControl>
Border>
Grid>
UserControl>

3. 新增 AnimationGridExample.xaml.cs
  • GridItemsAnimationGrid 的数据源;
  • IsSelectedCommand :当点击按钮时调用 AnimationGrid 的 ShowItem。
public partialclassAnimationGridExample : UserControl
{
public ObservableCollection GridItems
{
get { return (ObservableCollection)GetValue(GridItemsProperty); }
set { SetValue(GridItemsProperty, value); }
}

publicstaticreadonly DependencyProperty GridItemsProperty =
DependencyProperty.Register("GridItems", typeof(ObservableCollection), typeof(AnimationGridExample), new PropertyMetadata(null));
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(list);
}

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]

原文链接:
https://github.com/WPFDevelopersOrg/WPFDevelopers

[2]

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

[3]

反馈:
https://github.com/WPFDevelopersOrg/WPFDevelopers/issues/new

[4]

GitHub 源码地址:
https://github.com/WPFDevelopersOrg/WPFDevelopers/blob/dev/src/WPFDevelopers.Shared/Controls/AnimationGrid/AnimationGrid.cs

[5]

Gitee 源码地址:
https://gitee.com/WPFDevelopersOrg/WPFDevelopers/blob/dev/src/WPFDevelopers.Shared/Controls/AnimationGrid/AnimationGrid.cs

相关文章

单片机C语言编程,心得都在这里了

单片机写代码总踩坑,头文件被无视,老工程师的经验哪里来?前几天写8x8矩阵键盘的程序,搞了三天代码一直乱报错。后来发现自己连头文件是什么都不清楚,之前写的都是小程序,压根没碰过.h文件。看别人的程序都...

Linux系统编程—互斥量mutex(linux 互斥量)

##互斥量mutex前文提到,系统中如果存在资源共享,线程间存在竞争,并且没有合理的同步机制的话,会出现数据混乱的现象。为了实现同步机制,Linux中提供了多种方式,其中一种方式为互斥锁mutex(也...

打通 JAVA 与内核系列之 一 ReentrantLock 锁的实现原理

写JAVA代码的同学都知道,JAVA里的锁有两大类,一类是synchronized锁,一类是concurrent包里的锁(JUC锁)。其中synchronized锁是JAVA语言层面提供的能力,在此不...

关于异步信号安全(下面关于异步电路危害的描述错误的是)

线程安全与重入以及异步信号安全的区别. 可重入一定是线程安全的,但是线程安全不一定是可重入的. 引用别人的博客中的话吧.如下: http://blog.csdn.net/xiaofei0859/art...

掌握C语言多线程:高效并发编程指南

一、多线程基础概念介绍多线程编程是现代软件开发中提高程序性能和响应性的重要技术。在C语言中,pthread(POSIX Threads)库是实现多线程编程的标准工具。本节将通俗易懂地介绍多线程的核心概...

C++11 同步机制:互斥锁和条件变量

前段时间,我研究了 ROS2(Jazzy)机器人开发系统,并将官网中比较重要的教程和概念,按照自己的学习顺序翻译成了中文,进行了整理和记录。到目前为止,已经整理了20多篇文章。如果你想回顾之前的内容,...