简体   繁体   English

如何判断ItemsControl数据模板中的项目是否为最新?

[英]How to tell whether item in itemscontrol datatemplate is current?

I have an ItemsControl that binds to ICollectionView. 我有一个绑定到ICollectionView的ItemsControl。

I need to tell from withing DataTemplate of an item, whether it is the current. 我需要从关闭项目的DataTemplate来判断它是否是当前的。

Note: This is possible from Listbox, but I want ItemsControl looks. 注意:这可以从列表框中进行,但是我希望ItemsControl看起来像。

I would do it with a MultiValueConverter which compares the data-templated item with the CurrentItem in the view, eg 我会用一个MultiValueConverter来做到这一点,它将数据模板化的项目与视图中的CurrentItem进行比较,例如

<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. 另外, ItemsControlItemsSource显然需要为ICollectionView,但是无论如何,您都说是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM