Search code examples
c#wpfxamlitemscontrol

Highlight item in ItemsControl


I want to render a couple of elements using an ItemsControl, and highlight one of them

My ViewModel:

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

My XAML:

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

I want to highlight the item by setting the background property to something specific, how should I go on about it?


Solution

  • First have a converter which will compare reference of two objects say 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
    }
    

    And in XAML file, use converter to check if current item is same as highlighted item in ViewModel and in case converter returns true set the color of control using 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>
    

    Make sure you add converter as a resource in your xaml file.