Stumbling Through: WPF (Transparency Part II)
We left off last time with a simple form that has an image as its background. Not too impressive, and not what I set out to do with transparency! Let’s drag a listbox out there and plunk it down right in the center:
Ah, yes. That is exactly the look I want to avoid in this project. In order to see if our transparency is working, we’ll need to put a few items into the list. Normally, I would click it and use the properties explorer to find ‘Items’ and add to it that way, but I’ve already been disappointed by the property explorer one too many times so I will instead attempt it through the XAML. Logically, I would assume that list items would appear within the list box tag, so I open it up and see what intellisense tells me. That is one heck of a list of stuff that can be under a listbox, thankfully I spot ListBoxItem fairly quickly and add it. Now I was expecting the ListBoxItem to contain a text attribute, but one did not exist. Instead, I noticed a TextBlock attribute, which indicated to me that a ListBoxItem can be made up of, among other things, TextBlocks (WPF’s equivalent to labels in WinForms). So I add three ListBoxItems made up of text blocks to look like this:
<ListBox Margin="79,68,79,94" Name="listBox1" >
<ListBoxItem>
<TextBlock Text="Me"/>
</ListBoxItem>
<ListBoxItem>
<TextBlock Text="You"/>
</ListBoxItem>
<ListBoxItem>
<TextBlock Text="Somebody else entirely"/>
</ListBoxItem>
</ListBox>
Now that my list box is set up, let’s see what it takes to make it transparent. When trying to set the background of my window, I noticed that ‘transparent’ was an option there. Could it be so simple that I just tell the list box’s background to be transparent?
<ListBox Margin="79,68,79,94" Name="listBox1" Background="Transparent">
Holy cow, it worked!
I didn’t have to override a paint event or anything! I’m starting to like this WPF thing… However, we are not quite out of the woods. For one thing, my goal was to make a multi-line listbox which, if we increase the font size, we see that ugly horizontal scrollbar. Secondly, when we select an item, the whole transparency ‘coolness’ is obliterated by the default list box selection bar:
The next step is to correct both of those issues.