Search code examples
wpfitemscontrolcurrentitem

How to tell whether item in itemscontrol datatemplate is current?


I have an ItemsControl that binds to ICollectionView.

I need to tell from withing DataTemplate of an item, whether it is the current.

Note: This is possible from Listbox, but I want ItemsControl looks.


Solution

  • I would do it with a MultiValueConverter which compares the data-templated item with the CurrentItem in the view, e.g.

    <local:EqualityComparisonConverter x:Key="EqualityComparisonConverter"/>
    <DataTemplate DataType="{x:Type local:Employee}">
        <StackPanel Orientation="Horizontal">
            <CheckBox IsEnabled="False">
                <CheckBox.IsChecked>
                    <MultiBinding Converter="{StaticResource EqualityComparisonConverter}" Mode="OneWay">
                        <Binding RelativeSource="{RelativeSource AncestorType=ItemsControl}"
                                 Path="ItemsSource.CurrentItem"/>
                        <Binding />
                    </MultiBinding>
                </CheckBox.IsChecked>
            </CheckBox>
            ...
    

    The converter:

    public class EqualityComparisonConverter : IMultiValueConverter
    {
        #region IMultiValueConverter Members
    
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values.Length < 2) throw new Exception("At least two inputs are needed for comparison");
            bool output = values.Aggregate(true, (acc, x) => acc && x.Equals(values[0]));
            return output;
        }
    
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    
        #endregion
    }
    

    Make sure to actually change the current item in some way or it is quite pointless. Also the ItemsSource of the ItemsControl obviously needs to be a ICollectionView but you said that is the case anyway.