1

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.

Kugel
  • 19,354
  • 16
  • 71
  • 103
  • 2
    several things here: 1. a ListBox _is_ an ItemsControl (that also inherits from Selector, and thus can Select), so you actually get more with ListBox than with ItemsControl. To have the same looks just restyle the ListBox 2. [ICollectionView.CurrentItem](http://msdn.microsoft.com/en-us/library/system.componentmodel.icollectionview.currentitem.aspx) 3. this is not really an answer, because you didn't really specify a lot – Markus Hütter Apr 13 '11 at 15:10
  • @Markus your comment really told me nothing new. – Kugel Apr 13 '11 at 15:59

1 Answers1

3

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.

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Thank you, I was considering this, but I thought there would be a more simple solution. – Kugel Apr 13 '11 at 16:00