Tuesday, 15 February 2011

winforms - Windows Form - How add header not selectable in combobox item in C#? -



winforms - Windows Form - How add header not selectable in combobox item in C#? -

i need create custom combobox command allows header separator should not selectable using mouse move or key press.

this example:

header1 item1 item2 item3 header2 item4 item5

i tried many solutions, without success. in advance!

once again, wpf can provide solutions require tons of horrible hacks in winforms.

copy , paste code in file -> new project -> wpf application in visual studio.

you notice solution not provides different visual appearance header items, prevents unwanted selection, via mouse or keyboard, , doesn't need subclass regular combobox class, lead lesser maintainability.

xaml:

<window x:class="wpfapplication5.window2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:wpfapplication5" title="window2" height="300" width="300"> <grid> <combobox itemssource="{binding}" displaymemberpath="displaytext" verticalalignment="center" horizontalalignment="center" height="25" width="100"> <combobox.itemcontainerstyle> <style targettype="comboboxitem"> <setter property="foreground" value="black"/> <style.triggers> <datatrigger binding="{binding isheader}" value="true"> <setter property="isenabled" value="false"/> <setter property="fontweight" value="bold"/> </datatrigger> <datatrigger binding="{binding isheader}" value="false"> <setter property="margin" value="10,0,0,0"/> </datatrigger> </style.triggers> </style> </combobox.itemcontainerstyle> </combobox> </grid> </window>

code behind:

using system.collections.generic; using system.windows; namespace wpfapplication5 { public partial class window2 : window { public window2() { initializecomponent(); var list = new list<comboboxitem> { new comboboxitem {displaytext = "header1", isheader = true}, new comboboxitem {displaytext = "item1", isheader = false}, new comboboxitem {displaytext = "item2", isheader = false}, new comboboxitem {displaytext = "item3", isheader = false}, new comboboxitem {displaytext = "header2", isheader = true}, new comboboxitem {displaytext = "item4", isheader = false}, new comboboxitem {displaytext = "item5", isheader = false}, new comboboxitem {displaytext = "item6", isheader = false}, }; datacontext = list; } } public class comboboxitem { public string displaytext { get; set; } public bool isheader { get; set; } } }

c# winforms combobox

No comments:

Post a Comment