Search code examples
windowsmvvmuwpwin-universal-appmvvmcross

Customizing UWP ListViewItem by ViewModel


Asking for help. Is there any opportunity to change ContentBorder:BorderBrush of Listviewitem by the ViewModel {Binding}? Something like this


Solution

  • UPDATED

    You can create an ItemContainerStyleSelector, where you can apply custom style based on the current item in the list.

    public class CustomItemContainerStyleSelector : StyleSelector
    {
        public Style MyStyle1 { get; set; }
        public Style MyStyle2 { get; set; }
    
        protected override Style SelectStyleCore(object item, DependencyObject container)
        {
            var obj = (MyObject)item;
            if (/* Some kind of condition based on the bound object */)
            {
                return MyStyle1;
            }
            else
            {
                return MyStyle2;
            }
        }
    }
    

    You can use this style selector like this:

    <ListView ItemsSource="{Binding SomeList}">
        <ListView.ItemContainerStyleSelector>
            <local:CustomItemContainerStyleSelector>
                <local:CustomItemContainerStyleSelector.MyStyle1>
                    <Style TargetType="ListViewItem">
                        <Setter Property="BorderThickness" Value="5,0,0,0"/>
                        <Setter Property="BorderBrush" Value="Red"/>
                    </Style>
                </local:CustomItemContainerStyleSelector.MyStyle1>
                <local:CustomItemContainerStyleSelector.MyStyle2>
                    <Style TargetType="ListViewItem">
                        <Setter Property="BorderThickness" Value="5,0,0,0"/>
                        <Setter Property="BorderBrush" Value="Yellow"/>
                    </Style>
                </local:CustomItemContainerStyleSelector.MyStyle2>
            </local:CustomItemContainerStyleSelector>
        </ListView.ItemContainerStyleSelector>
    </ListView>