开发者

How to tell whether item in itemscontrol datatemplate is current?

开发者 https://www.devze.com 2023-02-24 18:50 出处:网络
I have an ItemsControl that binds to ICollectionView. I need to tell from withing DataTemplate of an item, whether it is the 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消