Skip to content

Instantly share code, notes, and snippets.

@BYJRK
Created March 16, 2023 08:59
Show Gist options
  • Save BYJRK/2e5d4fe3b67791ca818b468723826885 to your computer and use it in GitHub Desktop.
Save BYJRK/2e5d4fe3b67791ca818b468723826885 to your computer and use it in GitHub Desktop.
Two WPF converters used to get the item's index inside a ItemsControl
using System.Collections;
using System.Globalization;
using System.Windows.Data;
class ElementIndexConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length == 2 && values[0] is not null && values[1] is IList items)
return (items.IndexOf(values[0]) + 1).ToString();
return Binding.DoNothing;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
[ValueConversion(typeof(DependencyObject), typeof(string))]
class ItemIndexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is DependencyObject item)
{
var box = ItemsControl.ItemsControlFromItemContainer(item);
var index = box.ItemContainerGenerator.IndexFromContainer(item);
return (index + 1).ToString();
}
return string.Empty;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment