Hello,
I'm working at an C# WPF MVVM application with a XamCarouselListBox.
How can I archieve that the clicked item always moves to the middle?
Can I archieve this via XAML?
I always show 3 items at once with "ItemsPerPage = "3"".
Thanks,
Achim
Hi Achim,
Unfortunately it's not currently possible to get this working with XAML only. You will need to programmatically adjust what item is displayed as the main item in the carousel by using the XamCarouselListBox.ScrollInfo.SetHorizontalOffset() method. This method takes in the index of the item where you want to set the offset and the offset will place the item at the beginning of the carousel path. So if your path goes from left to right, the index you provide to the SetHorizontalOffset() method will place the item all the way to the left. So assuming you have 3 items displayed per page you will want to set the horizontal offset to (index - 1), taking care to handle index wrapping issues when you get to the edges of your data.
In order to keep MVVM you can put this logic into a Behavior<T> and then attach the behavior to the carousel in XAML. This way you don't have any code in your code-behind.
Hi Rob,
the problem is that I need a way to place a item in the focus/center of the carousel.
It doesn't even need to be clicked.
I use my carousel to avoid radio buttons, because a carousel is more dynamic.
But 1 special item always needs to be in the focus of the carousel on the startup of the program, because it's selected by default. It does look strange if the default-selected-item isn't even shown (ItemsPerPage="3").
I tried to understand the logic behind the carousel (which item is shown in the center by default) and replaced the item in the center with the selected item (I replaced it in my ObservableCollection). This worked fine, but I noticed that this logic changes when the number of total items in the carousel are changed.
What would you recommend?
Thanks, Achim
The carousel tries to space the items out evenly along the carousel path. If the ItemsPerPage is set to 3 then it will space 3 items out evenly. One at the start of the path, one at the end of the path and one right between the two. If you had 4 ItemsPerPage you would see that no item is in the exact middle.
So with 3 ItemsPerPage, if you want to center a particular item you need to get that item's index in the ItemsSource and then use the SetHorizontalOffset method as I have discussed in my previous post. SetHorizontalOffset will move the provided index to the start of the carousel path so if you want a specific item to be centered then you need to set the desired index minus 1 as the horizontal offset.
var desiredIndex = myDataSource.IndexOf(itemIwantCentered);carouselListBox.ScrollInfo.SetHorizontalOffset(desiredIndex - 1);
That's how you would control what item is "centered" in a 3 ItemsPerPage scenario.
thanks for your help!
If I need any further assistance, I will contact you.