Boy Meets 'Hello World'

Blogging the journey from College Grad to .NET Developer

  Home  |   Contact  |   Syndication    |   Login
  11 Posts | 0 Stories | 5 Comments | 0 Trackbacks

News

Archives

Post Categories

Wednesday, June 25, 2008 #

I've been working on a WPF program (which once again, as expected, justified my belief that I will never find enjoyment in programming any UI)...

Luckily, my program is just one-way... it is used for reporting, no input needed here besides just moving around. So, I implemented most of it in labels. Later I realized, however, that some of these labels have contents that a user of the program might want to copy and paste in another program. By default, you cannot highlight text on WPF labels, and I couldn't find any properties that changes this behavior.

Here is how I went about it, taking a TextBox and styling it until it looks like a label.

<Style x:Key="FauxLabel" TargetType="{x:Type TextBox}">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="{x:Null}"/>
    <Setter Property="BorderThickness" Value="4"/>
    <Setter Property="IsTabStop" Value="False"/>
</Style>

You need to be careful of is if you're data binding these FauxLabel's to read-only properties. I think that TextBox's have a different default binding mode, which will cause an InvalidOperationException is you try to bind it against a read-only property...

InvalidOperationException:
A TwoWay or OneWayToSource binding cannot work on the read-only property 'StartTime' of type 'MyDataObject'.

So, my full change from label->text box is as follows...

<Label Content="{Binding StartTime}"/>
...
<TextBox Text="{Binding StartTime, Mode=OneWay}"/>

Of course, you will need to also include the style if you're not using it by default (I'm making a new style that is based off the FauxLabel style and using that as default).

There might be other nuances I've missed, but this works for me.