c# - How do you highlight an item in a combobox using WPF? -


i have combobox filled list of objects. highlight item in combobox based on ishighlighted property of object.

i've tried writing own style no real success...

<style x:key="simplecomboboxitem" targettype="comboboxitem">         <setter property="focusvisualstyle" value="{x:null}" />         <setter property="template">             <setter.value>                 <controltemplate targettype="comboboxitem">                     <border name="border" padding="2" snapstodevicepixels="true">                         <contentpresenter x:name="contentpresenter" />                     </border>                     <controltemplate.triggers>                         <trigger property="isselected" value="true">                             <setter targetname="border" property="background" value="#ffcccccc"/>                         </trigger>                         <trigger property="tag" value="highlight" sourcename="contentpresenter">                             <setter property="background" targetname="border" value="#ffaaf3a0"/>                         </trigger>                     </controltemplate.triggers>                 </controltemplate>             </setter.value>         </setter>     </style> 

thanx in advance

this should work fine simple datatrigger.

your object class:

public class testobject {     public string name { get; set; }      public bool ishighlighted { get; set; }      public override string tostring()     {         return this.name;     } } 

xaml:

<window x:class="testwpf.mainwindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"         xmlns:local="clr-namespace:testwpf"         title="mainwindow">     <grid>         <stackpanel>             <combobox>             <combobox.resources>                 <style targettype="comboboxitem">                     <setter property="focusvisualstyle" value="{x:null}" />                     <setter property="background" value="gray" />                     <style.triggers>                         <datatrigger binding="{binding ishighlighted}" value="true">                             <setter property="background" value="red" />                         </datatrigger>                     </style.triggers>                 </style>             </combobox.resources>                 <local:employee name="nick" />                 <local:employee name="bob" ishighlighted="true" />                 <local:employee name="fred" />             </combobox>         </stackpanel>     </grid> </window> 

note: unlike sample above, i'm guessing in code you're binding combobox's itemssource... should work same. 1 thing careful of though, if object's 'ishighlighted' property can change, should implementing inotifyproperty changed ensure changing value notify ui triggers should refresh.


Comments