Skip to main content

How to: Handle the Click event for a carousel item

  • 2 minutes to read

Specify our own template for the ItemsControl.ItemTemplate property and handle the PreviewMouseDown event for the control in the ItemTemplate. In the PreviewMouseDown event handler, to make sure that the user clicks an active item, compare the DataContext property of the ActiveItem and sender; if they equal each other, the active item is clicked.

<Window x:Class="WpfApplication27.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
        xmlns:dxca="http://schemas.devexpress.com/winfx/2008/xaml/carousel"
        xmlns:local="clr-namespace:WpfApplication27"
        Title="Window1"
        Width="597"
        Height="339">

    <Window.Resources>
        <local:MyList x:Key="myList" />
    </Window.Resources>

    <dxca:CarouselItemsControl x:Name="carouselItemsControl" ItemsSource="{Binding Source={StaticResource myList}}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <dxca:CarouselPanel ActivateItemOnClick="True" AttractorPointIndex="2" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding Field1}" PreviewMouseDown="Button_PreviewMouseDown" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </dxca:CarouselItemsControl>

</Window>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Collections.ObjectModel;

namespace WpfApplication27 {
    public partial class Window1 : Window {
        public Window1() {
            InitializeComponent();
        }
        private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e) {
            if (((FrameworkElement)sender).DataContext == ((FrameworkElement)carouselItemsControl.Carousel.ActiveItem).DataContext)
                MessageBox.Show("ActiveItemIsClicked");
            Title = ((Button)sender).Content.ToString();
        }
    }
    public class MyList : ObservableCollection<MyObject> {
        public MyList() {
            Add(new MyObject() { Field1 = "a1", Field2 = "a2" });
            Add(new MyObject() { Field1 = "b1", Field2 = "b2" });
            Add(new MyObject() { Field1 = "c1", Field2 = "c2" });
            Add(new MyObject() { Field1 = "d1", Field2 = "d2" });
            Add(new MyObject() { Field1 = "e1", Field2 = "e2" });
        }
    }
    public class MyObject {
        public string Field1 { get; set; }
        public string Field2 { get; set; }
    }
}