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

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

maynowei7个月前 (08-16)技术知识62

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

相关文章

Objective-C的本质(objective-c的特点)

我们平时编写的Objective-C代码,底层实现其实都是C\C++代码,所以Objective-C的面向对象都是基于C\C++的数据结构实现的OC对象的本质Objective-C的对象、类主要是基于...

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

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

如何优雅地使用嵌入式事件标志组?

事件标志组嵌入式事件标志组是一种在嵌入式系统中广泛使用的同步机制,主要用于实现多任务间的同步与通信。事件标志组是一组事件标志位的集合,每个位代表一个事件是否发生。它允许任务等待特定的事件发生,当事件发...

Linux系统编程:条件变量为什么要用锁

条件变量可以解决线程同步和共享资源访问的问题,条件变量是对互斥锁的补充,它允许一个线程阻塞并等待另一个线程发送的信号,当收到信号时,阻塞的线程被唤醒并试图锁定与之相关的互斥锁。具体定义如下:等待:in...

英文美文分享: Reflect and Evolve (反思与进化)

“We do not learn from experience… we learn from reflecting on experience.” – John Dewey“我们不只是从经验中学习,...

Java基础:反射机制(java反射机制使用场景)

一、基本概念主要是指程序可以访问、检测和修改它本身状态或行为的一种能力, 并能根据自身行为的状态和结果,调整或修改应用所描述行为的状态和相关的语义。Java 中,反射是一种强大的工具。它使您能够创建灵...