简易的AutoPlayCarousel 轮播控件
原理是使用StackPanel 的margin属性的偏移来实现轮播的效果
废话不多说直接上代码
AutoPlayCarousel核心代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | [ContentProperty(nameof(Children))] [TemplatePart(Name = "PART_StackPanel" , Type = typeof (StackPanel))] public class AutoPlayCarousel : Control { #region Identifier /// <summary> /// 视图区域 /// </summary> private StackPanel _stkMain; /// <summary> /// /// </summary> private DispatcherTimer _dtAutoPlay; #endregion #region Constructor static AutoPlayCarousel() { DefaultStyleKeyProperty.OverrideMetadata( typeof (AutoPlayCarousel), new FrameworkPropertyMetadata( typeof (AutoPlayCarousel))); } public AutoPlayCarousel() { Loaded += AutoScrollCarousel_Loaded; SizeChanged += AutoScrollCarousel_SizeChanged; } #endregion #region RoutedEvent public static readonly RoutedEvent IndexChangedEvent = EventManager.RegisterRoutedEvent( "IndexChanged" , RoutingStrategy.Bubble, typeof (IndexChangedEventHandler), typeof (AutoPlayCarousel)); public event IndexChangedEventHandler IndexChanged { add => AddHandler(IndexChangedEvent, value); remove => RemoveHandler(IndexChangedEvent, value); } void RaiseIndexChanged( int newValue) { var arg = new IndexChangedEventArgs(newValue, IndexChangedEvent); RaiseEvent(arg); } #endregion #region Property /// <summary> /// get the children collection. /// </summary> public ObservableCollection<FrameworkElement> Children { get => (ObservableCollection<FrameworkElement>)GetValue(ChildrenProperty); private set => SetValue(ChildrenProperty, value); } public static readonly DependencyProperty ChildrenProperty = DependencyProperty.Register( "Children" , typeof (ObservableCollection<FrameworkElement>), typeof (AutoPlayCarousel), new PropertyMetadata( new ObservableCollection<FrameworkElement>())); /// <summary> /// get or set orientation /// </summary> public Orientation Orientation { get => (Orientation)GetValue(OrientationProperty); set => SetValue(OrientationProperty, value); } public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register( "Orientation" , typeof (Orientation), typeof (AutoPlayCarousel), new PropertyMetadata(Orientation.Horizontal)); /// <summary> /// get or set index /// </summary> public int Index { get => ( int )GetValue(IndexProperty); set => SetValue(IndexProperty, value); } public static readonly DependencyProperty IndexProperty = DependencyProperty.Register( "Index" , typeof ( int ), typeof (AutoPlayCarousel), new PropertyMetadata(0, OnIndexChanged)); /// <summary> /// Gets or sets animation duration. /// </summary> public TimeSpan AnimateDuration { get => (TimeSpan)GetValue(AnimateDurationProperty); set => SetValue(AnimateDurationProperty, value); } public static readonly DependencyProperty AnimateDurationProperty = DependencyProperty.Register( "AnimateDuration" , typeof (TimeSpan), typeof (AutoPlayCarousel), new PropertyMetadata(TimeSpan.FromSeconds(0.5))); /// <summary> /// Gets or sets recyclable. /// </summary> public bool Recyclable { get => ( bool )GetValue(RecyclableProperty); set => SetValue(RecyclableProperty, value); } public static readonly DependencyProperty RecyclableProperty = DependencyProperty.Register( "Recyclable" , typeof ( bool ), typeof (AutoPlayCarousel), new PropertyMetadata( false )); public TimeSpan AutoPlayInterval { get => (TimeSpan)GetValue(AutoPlayIntervalProperty); set => SetValue(AutoPlayIntervalProperty, value); } public static readonly DependencyProperty AutoPlayIntervalProperty = DependencyProperty.Register( "AutoPlayInterval" , typeof (TimeSpan), typeof (AutoPlayCarousel), new PropertyMetadata(OnAutoPlayIntervalChanged)); #endregion #region Event Handler public override void OnApplyTemplate() { base .OnApplyTemplate(); _stkMain = GetTemplateChild( "PART_StackPanel" ) as StackPanel; } private void AutoScrollCarousel_SizeChanged( object sender, SizeChangedEventArgs e) { foreach (FrameworkElement children in Children) { children.Width = ActualWidth; children.Height = ActualHeight; } } private void AutoScrollCarousel_Loaded( object sender, RoutedEventArgs e) { if (Children == null ) return ; Loaded -= AutoScrollCarousel_Loaded; foreach (FrameworkElement child in Children) { child.Width = ActualWidth; child.Height = ActualHeight; } } private static void OnAutoPlayIntervalChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var autoScrollCarousel = d as AutoPlayCarousel; autoScrollCarousel?.RestartAutoPlayTimer(); } private void DispatcherTimerAutoPlay_Tick( object sender, EventArgs e) { Index++; } private static void OnIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var autoScrollCarousel = d as AutoPlayCarousel; if (autoScrollCarousel == null || !autoScrollCarousel.IsLoaded) return ; var targetIndex = 0; if (!autoScrollCarousel.Recyclable) targetIndex = autoScrollCarousel.Index > (autoScrollCarousel.Children.Count - 1) ? autoScrollCarousel.Children.Count - 1 : (autoScrollCarousel.Index < 0 ? 0 : autoScrollCarousel.Index); else targetIndex = autoScrollCarousel.Index > (autoScrollCarousel.Children.Count - 1) ? 0 : (autoScrollCarousel.Index < 0 ? autoScrollCarousel.Children.Count - 1 : autoScrollCarousel.Index); if (targetIndex != autoScrollCarousel.Index) { autoScrollCarousel.Index = targetIndex; return ; } autoScrollCarousel.ResetAutoPlayTimer(); if (autoScrollCarousel.Orientation == Orientation.Vertical) { autoScrollCarousel._stkMain.BeginAnimation(StackPanel.MarginProperty, new ThicknessAnimation() { To = new Thickness(0, -1 * autoScrollCarousel.ActualHeight * autoScrollCarousel.Index, 0, 0), Duration = autoScrollCarousel.AnimateDuration, EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseOut } }); } else { autoScrollCarousel._stkMain.BeginAnimation(StackPanel.MarginProperty, new ThicknessAnimation() { To = new Thickness(-1 * autoScrollCarousel.ActualWidth * autoScrollCarousel.Index, 0, 0, 0), Duration = autoScrollCarousel.AnimateDuration, EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseOut } }); } autoScrollCarousel.RaiseIndexChanged(targetIndex); } #endregion #region Function private void RestartAutoPlayTimer() { if (_dtAutoPlay != null ) { _dtAutoPlay.Stop(); } if (AutoPlayInterval.TotalSeconds != 0) { _dtAutoPlay = new DispatcherTimer() { Interval = AutoPlayInterval, }; _dtAutoPlay.Tick += DispatcherTimerAutoPlay_Tick; _dtAutoPlay.Start(); } } private void ResetAutoPlayTimer() { if (_dtAutoPlay != null ) { _dtAutoPlay.Stop(); _dtAutoPlay.Start(); } } #endregion } |
一些辅助代码
1 2 3 4 5 6 7 8 9 10 11 | public class IndexChangedEventArgs : RoutedEventArgs { public IndexChangedEventArgs( int currentIndex, RoutedEvent routedEvent) : base (routedEvent) { CurrentIndex = currentIndex; } public int CurrentIndex { get ; set ; } } public delegate void IndexChangedEventHandler( object sender, IndexChangedEventArgs e); |
AutoPlayCarousel默认的样式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <br><Style TargetType= "{x:Type local:AutoPlayCarousel}" > <Setter Property= "SnapsToDevicePixels" Value= "{StaticResource DefaultSnapsToDevicePixels}" /> <Setter Property= "FontSize" Value= "{StaticResource DefaultFontSize}" /> <Setter Property= "Template" > <Setter.Value> <ControlTemplate TargetType= "{x:Type local:AutoPlayCarousel}" > <StackPanel x:Name= "PART_StackPanel" Orientation= "{TemplateBinding Orientation}" > <ItemsControl x:Name= "PART_ItemsControl" ItemsSource= "{TemplateBinding Children}" VerticalAlignment= "Stretch" HorizontalAlignment= "Stretch" > <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Width= "{TemplateBinding Width}" Height= "{TemplateBinding Height}" Orientation= "{Binding Orientation,RelativeSource={RelativeSource AncestorType=local:AutoPlayCarousel}}" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> |
<sys:Double x:Key="DefaultFontSize">14</sys:Double>
<sys:Boolean x:Key="DefaultSnapsToDevicePixels">false</sys:Boolean>
页面使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <customControl:AutoPlayCarousel x:Name= "Carousel" AutoPlayInterval= "0:0:3" Recyclable= "True" Height= "1080" > <Grid Background= "Red" > <Grid HorizontalAlignment= "Center" VerticalAlignment= "Center" Height= "500" Width= "500" Background= "Black" > <TextBlock Text= "1" FontSize= "20" Foreground= "Wheat" HorizontalAlignment= "Center" VerticalAlignment= "Center" ></TextBlock> </Grid> </Grid> <Grid Background= "Green" > <Grid HorizontalAlignment= "Center" VerticalAlignment= "Center" Height= "500" Width= "500" Background= "Black" > <TextBlock Text= "2" FontSize= "20" Foreground= "Wheat" HorizontalAlignment= "Center" VerticalAlignment= "Center" ></TextBlock> </Grid> </Grid> <Grid Background= "Yellow" > <Grid HorizontalAlignment= "Center" VerticalAlignment= "Center" Height= "500" Width= "500" Background= "Black" > <TextBlock Text= "3" FontSize= "20" Foreground= "Wheat" HorizontalAlignment= "Center" VerticalAlignment= "Center" ></TextBlock> </Grid> </Grid> <Grid Background= "Blue" > <Grid HorizontalAlignment= "Center" VerticalAlignment= "Center" Height= "500" Width= "500" Background= "Black" > <TextBlock Text= "4" FontSize= "20" Foreground= "Wheat" HorizontalAlignment= "Center" VerticalAlignment= "Center" ></TextBlock> </Grid> </Grid> </customControl:AutoPlayCarousel> |
效果如下:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」