Tuesday, April 21, 2009

Custom Text Runs, Data Binding and cheating...

Faisel sent posted a question:

'Hi,
I have a requirement of showing additional text in a TextBlock. I have a Class in my silverlight application. I want to bind two of the properties in a TextBlock in my main page and show text something like this : "You make me feel - BONFIRE ".
The first part of the text here is a song name and the second part here is artist name. I need to show artist name based on the song name. For example if song is by another artist. It will show song name - "Still loving you - SCORPIONS" .
I tried to bind the Text property of the run to bind the Artist property to show the additional text in the TextBlock. There's some example of WPF which binds the Text property of Run by creating a BindableRun Class which derives from Run. But the problem in Silverlight is Run Class is Sealed in Silverlight.
Is there anyone who can help me to get the desired result. Someone please help me.'

I did the following response that I thought was interesting :) if it might make a few cringe... lol

one easy method would be to loose the binding. I know alot of people would be freaked out and this totally feeds into Dr. WPF's MVpoo design pattern but you could do something like this, so lets say we have this xaml that looks like this:

<stackpanel name="MyPanel" orientation="Vertical">
<button type="submit" content="add" click="Button_Click">
</stackpanel>

so the button doesn't need to be there and we could use a scroll panel or custom control but any element with a children collection would work. but in this case lets say we have this method button_click which contains this code:

TextBlock ThisBlock = new TextBlock();
//ThisBlock.Style = [whatever]...
ThisBlock.Text = Guid.NewGuid().ToString();
Run NewRun = new Run();
//Run.FontStyleProperty = ...
NewRun.Text = " ABC ";

ThisBlock.Inlines.Add(NewRun);
MyPanel.Children.Add(ThisBlock);

so each time you click the button you gets some text with a 'Run' at the end. to translate to the real solution when you load the page or get this data you need to parse it on your own in a loop and depending on some condition change the run context but you could also bind events and do other things at that time. of course you loose the whole data binding but really what it comes down to is does your code do the job?

the thread can be found at:

'http://dotnetslackers.com/Community/forums/showing-additional-text-in-a-textblock/t/3169.aspx '

anyway I know its a hacky way of doing things but hey, that is what 'hackingsilverlight' is all about :)