突出显示ItemsControl中的项目

时间:2013-03-27 16:45:21

标签: wpf itemscontrol

我想使用ItemsControl渲染几个元素,并突出其中一个

我的ViewModel:

public class ViewModel
{
    public List<Item> Items;
    public Item HighlightedItem;
}

我的XAML:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <myUserControl Background="{?}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

我想通过将背景属性设置为特定的内容来突出显示该项目,我该如何继续呢?

1 个答案:

答案 0 :(得分:1)

首先有一个转换器,它将比较两个对象的引用,如ObjectEqualsConverter

public class ObjectEqualsConverter : IMultiValueConverter
{
    #region IMultiValueConverter        

    public object Convert(object[] values, Type targetType, object parameter,
                          CultureInfo culture)
    {
        return values[0] == values[1];
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, 
                                CultureInfo culture)
    {
        throw new NotImplementedException();
    } 
    #endregion
}

XAML文件中,使用转换器检查是否为current item is same as highlighted item in ViewModel,如果转换器返回true,则使用color设置控件的trigger -

   <ItemsControl ItemsSource="{Binding Items}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <myUserControl x:Name="myControl" />
                <DataTemplate.Triggers>
                    <DataTrigger Value="True">
                        <DataTrigger.Binding>
                            <MultiBinding Converter="{StaticResource ObjectEqualsConverter}">
                                <Binding/>
                                <Binding Path="DataContext.HighlightedItem" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}"/>
                            </MultiBinding>
                        </DataTrigger.Binding>
                        <Setter TargetName="myControl" Property="Background" Value="Red"/>
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

确保在xaml文件中添加转换为resource