Category Archives: .NET

Smugmug API

Smugmug Logo SmallMy photo sharing site of choice is Smugmug. I can upload and view images at their original size, they offer effectively unlimited storage, support video streaming, protected sharing facilities and the website doesn’t suck. It comes with a price tag but I’m fine with that.

Over the last six months I’ve been playing with the Smugmug API. To date its been a somewhat painful experience. Roughly three months ago they introduced an additional security measure that meant most of the API calls required an additional parameter – which wasn’t documented on the API wiki (the _su cookie).

RestSharp LogoThere are a number of helper wrappers already written for the API (though some are out of date) – but I figured it would be a good learning experience to put together something small for my own requirements. I decided on using the REST flavour of the API and initially implemented it with WebClient. However, after following up on a tip I got from attending the New York Windows Phone User Group I switched to RestSharp (using VS NuGet package installer) which made the code much more concise.

My most recent attempt was to add a feature to the application I’m writing that would allow me to view statistics for my Smugmug galleries. The website offers access to these statistics but in a pretty limited fashion. Having found an API (method.albums.getStats) I figured I could create a stats summary that was exactly was I was after. After several frustrating hours of tweaking the API call and getting nothing but zero hit counters back I resorted to Google. Sure enough – it seems that the API method doesn’t work, and in fact has been broken for months. Would be nice to have that kind of information on the API Wiki page, no?

Silverlight Firestarter 2010

Silverlight Firestarter 2010 Banner

Spawned from a communication at the recent PDC that was then somehow twisted and blown well out of proportion by the blogosphere, Microsoft recently held a Silverlight Firestarter event on campus in Redmond (and streamed live). The “main event” was the keynote which was primarily dedicated to talking about the future of Silverlight, and specifically show casing Silverlight 5.

What was announced

The current feature set of Silverlight 5 is impressive – see Scott Gu’s blog post for a comprehensive overview, the official futures page, or better yet go watch the keynote here.

Here’s what I’m looking forward to the most:

  • Implicit DataTemplates. How do Silverlight developers survive without this!?
  • AncestorType support for RelativeSource binding.
  • Data binding debugging. This looks awesome and could be a real time saver. Simply place a breakpoint on the binding declared in the XAML. When the debugger stops it gives you full access to the Target and binding results or error. This surely has to make it into WPF in an upcoming Visual Studio service pack, or at the very least vNext.
  • For shear, jaw dropping visual effect the 3D medical modelling and globe demos were spectacular. Though it was a very quick portion of the demo the 3D globe – with separate land and cloud layers looked great. I hope this is the future for Bing maps now that they’ve scrapped the 3D plug-in version.
  • BI with Project Crescent. So this offering was shown at the recent PASS 2010 Summit and its seriously cool.


The problem of course is that the release date for Silverlight 5 isn’t until late 2011 – effectively a year away. Its understandable that Microsoft hadn’t originally planned on showing off Silverlight 5 until they were closer to the release – probably at the time the first beta (scheduled for Spring 2011). It seems they felt that their hand was forced by the recent “Silverlight is dead” debacle. What I saw demoed was certainly impressive but it really makes me crave those features now – and makes Silverlight 4 seem more incomplete as a result. It isn’t helped that Silverlight for Windows Phone is currently not even at Silverlight 4 level. So for now I get to develop on Silverlight 3.5 and 4.0 whilst eagerly awaiting the promise that is Silverlight 5.

Of course any serious development I do is in WPF – ‘cause lets face it – browser dependent apps are just toys right?

Intro Sessions for Silverlight

The rest of the Firestarter event was devoted to standard presentation sessions. It started with a Silverlight Binding 101 session given by Jesse Liberty. This should have been dull, but Jesse was very entertaining. If you’re very new to the Silverlight scene I strongly recommend his session as an introduction. John Papa also did a very good introduction to MVVM session.

Each session gradually increased in terms of depth of coverage. The last session by Jamie Rodriguez was a fast and furious dive into potential performance issues when developing for Windows Phone 7. It covered many pragmatic tips and tricks on monitoring and resolving these issues. Despite having seen much of this content previously presented by Jamie on Channel 9 I still found it to be a great session.

The Venue

Microsoft Campus SignThis was my first trip to Seattle and unfortunately I was on a very tight schedule. I arrived very early Thursday morning and left the same night (with 6 hours of flight time either side). I caught the local bus from my hotel in Bellevue to the campus and the area looked very suburban, yet very beautiful too (certainly compared to the concrete jungle that is Manhattan). I also had a detour through downtown Seattle on the way back to the airport in a taxi I was sharing. I was impressed with the city, though I’m told the real test as to whether you could live in Seattle is being able to live through your first winter there.

The event was held in Building 33 at the Conference Center. The room used to host the keynote and the developer sessions was a lecture theatre layout. This was awesome ‘cause it meant everyone could have their laptops set up the entire day, plugged in to power, recharging phones etc. I think about one third of the attendees at the keynote were Microsoft employees from teams other than the Silverlight team.

Is Silverlight Resuscitated?

So will this Firestarter event satisfy the seemingly fickle Silverlight development community? Will they be prepared to wait more that 12 months between versions (shock, gasp)! I heard someone in the audience complain that there wasn’t enough Windows Phone content – which was kind of amusing. Too much focus on Windows Phone would have probably been exactly the wrong message to send to the community.

So where does this leave WPF? No mention in the PDC keynote, no separate Firestarter event – is WPF dead!? Bring on WPF Firestarter 2011 Smile with tongue out

Charles Petzold at the NYC .NET Developers Group

Tonight I went along to the New York City .NET User Group to watch Charles Petzold presenting on Windows Phone 7. It was fun to see Petzold in person and though its obvious he’s more an author than a public speaker he still did a great job. He was very well prepared for the talk and did his best to accommodate the somewhat rowdy crowd. The talk was an introduction to the Windows Phone 7 development experience with a focus on the application lifecycle – specifically tombstoning. This seemed to be at the right level for the crowed as far as I could tell – it seemed the majority of people there knew very little about the new platform.

I’d never been to a NYC .NET Developers Group meeting before. There was a pretty good turnout, well over a hundred people. For me though the event was certainly tarnished by the general lack of organization and some inane questions/observations from the audience.

Firstly the pizzas. Charles did a very polished job of starting his talk with a reflection on how mobile devices have become ubiquitous. He then manoeuvred this into an introduction of Windows Phone 7. He had his talk prepared on a set of notes which he would keep glancing at, but I began not to notice that as I was drawn into the talk. At about 10 minutes in just as he has found his stride and captured the audience the pizzas arrived. Some people didn’t even wait for Charles to stop speaking, they just got up and went to the back of the room to help themselves. Eventually one of the organizers walked up the front and cut Charles off mid-sentence – suggesting now would be a good time for a break. I think his response was something like “ah… err… yeah ok”.

Then there were the questions from the audience. A few people asked questions during the talk. In my mind it wasn’t really appropriate given the size of the audience and the style of presentation – more of a keynote. However, Charles hadn’t asked people to leave questions to the end and I understand that people are probably used to asking questions during a user group presentation. What was really annoying though were some of the questions themselves. Interrupting someone to ask them whether xyz is supported when it should have been clear he was just about to get to that. At the end of the session one guy from the audience went on a completely misinformed rave about the price of phones (including the prices in Pakistan!) , another was asking what video formats were supported, etc. These questions couldn’t be answered by Charles and the organizers (or Microsoft) hadn’t thought to have someone up front with him to answer them. Charles managed to stay very well composed throughout.

One more amusing crowd moment was during the impromptu pizza break. Charles was patiently waiting for us all so a few attendees quite understandably took the opportunity to get a book signed, introduce themselves or ask some questions about the phone or his upcoming book. Charles was actually using his Windows Phone 7 device to run the PowerPoint presentation for his talk. He had the device setup at the front on a stand with a video camera so it could be projected onto the screens. So he’s standing there talking to a few people with the phone next to him on the stand at the current PowerPoint slide. One guy walks up and asks if he can play with the phone. “What now? Err.. . no.”. I’m sure the guy was just eager to get his hands on a real device but imagine someone asking you if they can play with your laptop half way through giving a well scripted talk/demo to a packed room of people? Seriously? Oh well… I got a chuckle out of it.

Word Puzzle to Sliverlight Phone–Part 3

Last night I dusted off Word Puzzle and decided to try out tombstoning in Window Phone 7 – just to see how much of a pain this is really going to be. The first hurdle I had was to convert the existing solution from the Windows Phone CTP to the Beta release. This turned out to be quite a bit harder than I had expected. On the upside I got a pretty good idea of some of the changes that were made – ditching the resource files, using the manifest to nominate the launch window, assembly consolidation etc.

Once I had eventually gotten it to work with the Beta I decided to create a Settings page so that I could:
1) test the navigation and
2) have a simplified state object to persist to the application cache whilst de-activating.

The settings page looked like this:


It was bound to some of the properties on my pre-existing LetterBoardSetup class, e.g. AllowBackwards, AllowDiagonal, Width, Height.

I added the following code to my App.xaml.cs file and everything worked just fine.

private void Application_Activated(object sender, ActivatedEventArgs e)
var myState = PhoneApplicationService.Current.State;
settings = myState["settings"] as LetterBoardSetup;
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
var myState = PhoneApplicationService.Current.State;
myState["settings"] = settings;

When the application de-activates the state is saved, then restored correctly on re-activation. I decided to move on and save off the actual game state. The easiest (laziest) way to save the game state seemed to be to just save off the entire object graph (after all we are talking about a very trivial game here). Several of my classes had private setters for public properties. No problem I figured – I’ll just use DataContract from System.Runtime.Serialization namespace/assembly. This does all sorts of wonderful things – like allowing private fields to be serialized, creating instances without invoking any constructors and the like. At least I thought that’s how it worked – and on the full .NET framework I would have been right. Through trial and error I determined that the Silverlight version doesn’t have these capabilities – classes are required to have public setters and getters for properties (yuerk!).

So – in the mindset of just “getting it done” I went through and opened up my object model – changing private setters to public, making getters do “on-demand” construction for things like collections etc. to make it more serialization friendly.

Now I have a version of WordPuzzle that runs in the emulator and survives tombstoning with absolutely no data loss. Should I ever want to I also now have a version that could easily allow games to be saved. In fact all that’s really left to do is find a couple of images for the application bar buttons – oh – and actually make the game play itself something slightly more err… exciting.

Preventing a bound TextBox from resetting the caret position

Someone posed a question on our internal mailing list today at work that reminded me of a problem I’d tackled previously whilst working as a developer of fortune.

Here’s the challenge. A TextBox is bound to a data value that is being constantly updated. In my scenario the TextBox was bound to a data feed coming from a serial port connected weigh bridge. Even though the value is being automatically updated the operator has the ability to override the value with their own – at which point it would normally cease being updated by the data service.

Sounds fairly straight-forward. The main problem is that every time the TextBox value is updated via data-binding the selection text and position of the caret is reset. This is particularly annoying if the operator positions the caret about to make their change and a fraction of a second before they press a key the caret moves to the left edge.

I can’t remember exactly how we solved this problem in my earlier engagement (Raaj if you’re listening you could jog my memory) but here was my quick re-attempt.

First I’ll set the scene with a mock environment.

public partial class MainWindow : Window
private ViewModel viewModel;
private DispatcherTimer timer;
public MainWindow()
this.viewModel = new ViewModel();
this.DataContext = viewModel;
this.timer = new DispatcherTimer(
new TimeSpan(0, 0, 1),
this.Dispatcher); } private void UpdateValue(object sender, EventArgs e) { this.viewModel.Value += 0.01; } }

This sets up a simple form whose DataContext refers to a ViewModel with a Value property. The Value property is updated every second by a thread safe timer.

<Window x:Class="TextBoxOverlay.MainWindow"
Title="MainWindow" Height="350" Width="525">
<StackPanel Width="150">
Text="{Binding Value,StringFormat=0.00,UpdateSourceTrigger=PropertyChanged}"/>

The XAML simple binds a TextBox to the Value property. Running this sample and the problem can be immediately realised. Attempting to edit the value in the TextBox using the keyboard is extremely frustrating. The caret won’t go where you want it to.

So – the next step is to create a TextBlock that overlays the TextBox and instead bind this to the Value property. We set the IsHitTestVisible property on this TextBlock to False so that the user can still interact with the TextBox underneath. Then – and this is where things get a little sneaky – we make the TextBox’s text transparent. This allows us the strange freedom to interact with the TextBox’s content by selecting it and moving the caret – and because we can see the same text in the overlaid TextBlock things appear as normal.

<Window x:Class="TextBoxOverlay.MainWindow"
Title="MainWindow" Height="350" Width="525">
<StackPanel Width="150">
Text="{Binding ModifiedValue,StringFormat=0.00,
PreviewTextInput="TextBoxPreviewTextInput" Foreground="Transparent"/> <TextBlock IsHitTestVisible="False" Margin="5,0" Text="{Binding Value,StringFormat=0.00}"/> </Grid> </StackPanel> </Grid> </Window>

You can see from the XAML that the TextBox is bound to a new field on our ViewModel called ModifiedValue. We also hook up to the PreviewTextInput event. We could have used an attached behaviour here rather than resorting to code-behind – but I wanted to keep things simple. So the code behind on the form has:

        private void TextBoxPreviewTextInput(object sender, TextCompositionEventArgs e)
var textBox = sender as TextBox;
var selectionStart = textBox.SelectionStart;
var selectionLength = textBox.SelectionLength;
var caretIndex = textBox.CaretIndex;
this.viewModel.ModifiedValue = this.viewModel.Value;
textBox.CaretIndex = caretIndex; 
textBox.SelectionStart = selectionStart; textBox.SelectionLength = selectionLength; }

Here we save and restore the TextBox’s SelectionStart, SelectionLength and CaretIndex whilst updating the ModifiedValue that is about to be changed to equal the Value that the user can actually see (remember the ModifiedValue is transparent).

The very last trick is within the ModifiedValue’s setter where we update the Value property. This ensures that whatever changes the operator makes to the TextBox are visible in the overlaid TextBlock. Of course the whole point of doing all of this is that the caret position and selection remains completely unchanged whilst the value appears to update.

        public double? ModifiedValue
return this.modifiedValue;
if (this.modifiedValue != value)
this.modifiedValue = value;
if (this.ModifiedValue.HasValue)
Value = ModifiedValue.Value;

Source code here.

So aside from the tacky code-behind to keep the code here to a minimum, I’m wondering if there isn’t a neater solution?

UPDATE: Using an attached behaviour

It was pointed out to me by a colleague that there is a simpler, more versatile solution. Simple encapsulate the text change with selection restore within an attached property. Then we can use multiple bindings to achieve the effect.

        public static string GetNonIntrusiveText(DependencyObject obj)
return (string)obj.GetValue(NonIntrusiveTextProperty);
public static void SetNonIntrusiveText(DependencyObject obj, string value)
obj.SetValue(NonIntrusiveTextProperty, value);
public static readonly DependencyProperty NonIntrusiveTextProperty =
typeof(TextBoxExtensions), new FrameworkPropertyMetadata(
NonIntrusiveTextChanged)); public static void NonIntrusiveTextChanged(
object sender,
DependencyPropertyChangedEventArgs e) { var textBox = sender as TextBox; if (textBox == null) return; var caretIndex = textBox.CaretIndex; var selectionStart = textBox.SelectionStart; var selectionLength = textBox.SelectionLength; textBox.Text = (string) e.NewValue; textBox.CaretIndex = caretIndex; textBox.SelectionStart = selectionStart; textBox.SelectionLength = selectionLength; }

Now the XAML no longer requires the tricky TextBlock overlay, we simple have a TextBox with two bindings.

Text="{Binding Value,StringFormat=0.00,
local:TextBoxExtensions.NonIntrusiveText="{Binding Value,StringFormat=0.00,

Conditional Formatting of a TextBox


I recently came across a scenario where I needed to bind a TextBox to a domain property but also have the value formatted for display. To make things more interesting the format was to be dynamic and the value needed to be editable.

The initial investigation led me to consider a ValueConverter. Ideally the TextBox.Text property could be bound and the Converter could be used to format to/from the required on-screen value. For a dynamic format it would be nice to bind the ConverterParameter to a property that exposed the format. Of course that doesn’t work because ConverterParameter doesn’t support data binding. I found a hack that gets around this – but it isn’t pretty. There are also some examples of using a MultiValueConverter and passing both the value to format and the format string itself as separate individual bindings. This approach has some difficulties too when converting both ways and its just feels like an abuse of the ValueConverter.

This lead me to think about the problem a little more… maybe a different approach is required? Thinking back to the WinForms days and I realised that I had solved this problem before, several times in fact. My approach to this problem for WinForms had been:

  • Subclass TextBox and add a Value property of type object that allows data binding to data types other than just string. Common types that could be used with a TextBox include int, decimal, double, bool, DateTime and enums.
  • The inherited TextBox also has a Format property. On GotFocus the Value property is formatted and used to populate the Text property. On LostFocus the reverse happens, the Text property is parsed back into the Value property. Of course this requires the data type to be known so a DataType property is required as well.

The benefits that this has:

  • TextBox works for data types other than string.
  • The value is formatted as required for display but upon data entry (GotFocus) the formatting is removed. This actually makes it easier to enter/modify the value because you don’t need to parse currency symbols, percentage signs and the like.

So the approach sounds good and its worked well for me in WinForms but its… well… not very WPF’ish. Upon starting any major development the first requirement in WinForms was to subclass all the controls – because they were just so lacking if functionality and even more importantly didn’t expose a common set of interfaces. However, I very rarely subclass controls in WPF – instead we can use attached behaviors to extend the control.

The attached behaviors required are:

  • object TypedValue
  • Type DataType 
  • string StringFormat

In XAML instead of binding to the TextBox.Text property we bind to the TypedValue attached property. The StringFormat can also be bound. The DataType can be inferred by the TypedValue – but for nullable types its best to be set explicitly. With a sample class as follows:

public class ModelItem
public object Value { get; set; }
public string Format { get; set; }

The XAML is then:

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
<DataGridTextColumn Header="Any Type TextBox">
<Style TargetType="{x:Type TextBlock}">
<Setter Property="local:TextBoxExtensions.StringFormat" Value="{Binding Format}"/>
<Setter Property="local:TextBoxExtensions.TypedValue" Value="{Binding Value}"/>
<Style TargetType="{x:Type TextBox}">
<Setter Property="local:TextBoxExtensions.StringFormat" Value="{Binding Format}"/>
<Setter Property="local:TextBoxExtensions.TypedValue" Value="{Binding Value}"/>
<DataGridTextColumn Header="Format" Binding="{Binding Format}" IsReadOnly="True"/>
<DataGridTextColumn Header="Value" Binding="{Binding Value}" IsReadOnly="True"/>

Which generates a DataGrid bound to a collection of ModelItems. Each ModelItem allows a different data type and format to be applied – great for a “user-defined fields” scenario.

Populating the ModelItems collection as follows in our main ViewModel:

    public class Model
public Model()
Primary = new ModelItem() { Format = "{0:#,##0.0}", Value = 12345678.765 };
Items = new ObservableCollection<ModelItem>();
Items.Add(new ModelItem() { Format = "{0:C2}", Value = 123.42 });
Items.Add(new ModelItem() { Format = "{02}", Value= 0.125 });
Items.Add(new ModelItem() { Format = "{0}", Value = "Fred" });
Items.Add(new ModelItem() { Format = null, Value = true });
Items.Add(new ModelItem() { Format = "Uncle {0}", Value = "George" });
Items.Add(new ModelItem() { Format = null, Value = Colors.Black });
Items.Add(new ModelItem() { Format = null, Value = System.DayOfWeek.Monday });
Items.Add(new ModelItem() { Format = "{0:0;minus 0;zip}", Value = -123.4 });
public ModelItem Primary { get; set; }
public ObservableCollection<ModelItem> Items { get; private set; }

Generates the following grid, which allows for editing of the strongly typed values.


Word Puzzle to Silverlight Phone – Part 2

Finally got interaction and feedback happening on the Silverlight port of Word Puzzle. This was so much more difficult than I had imagined – feels like learning WPF from scratch. I am beginning to believe that it would be easier to approach Silverlight with no WPF knowledge whatsoever.

  • I had to cater for not having DataTriggers – and then not being able to get behaviours/triggers/states to work like I wanted. In the end I used a ValueConverter to hack the selection and solved colours – yuk!
  • Had some weird issues with the MouseMove event – had to use CaptureMouse to get position readings outside the original UI element – wasn’t a requirement for WPF.
  • Spent ages working through really minor bugs that just aren’t reported properly in Silverlight. Things as simple as referencing a resource that doesn’t exist (due to misspelling) generates a super generic error message.
  • Had to create a proper custom layout panel for the words to position and rotate the highlight boxes. This was actually an improvement on the original version.

Anyhow – now have a playable version on the emulator. Slow progress, but progress nonetheless.

WordPuzzle_Stage2  WordPuzzle_Stage2_EndGame

Porting WPF Word Puzzle to Windows Phone Silverlight – Part 1

To date I’ve avoided doing any serious development in Silverlight. Every time I’ve tried to tackle it I get so frustrated with all the missing pieces. Besides which I’ve never had a good reason to do any Silverlight work – I’ve never been a fan of applications that run in a browser.

With the release of the Windows Phone Series development tools however, I now have a good reason. So I figured I’d pick a relative simple, small scale WPF application that actually makes some sense to run on a mobile device. Rather than starting it from scratch I just wanted to port it from WPF – so I chose the Word Puzzle program that I wrote a couple of years back. I figured it was a good choice because it met the criteria above, plus I’d already stripped it back a little to make sure it could run as an XBAP application.

Inspired by Rob’s posts on porting NProf to Silverlight I thought it may be of some interest to list off the issues that I come up against as I go through the process of porting. This first list represents me starting a new Windows Phone project and copying over classes and XAML files to get something to compile and look recognizable. The following represents about 2 hours work:


However, along the way I came across this list of issues:

  • No Viewbox
  • No MouseDown or MouseUp
  • No UniformGrid
  • No Image.StretchDirection
  • x:Type is not supported
  • No Style.Triggers
  • No DockPanel
  • No RoutedCommand
  • No KeyGesture
  • No DataType on DataTemplate?
  • No ValueConversion
  • No DefiningGeometry on Shape
  • No BooleanToVisibilityConverter
  • No DynamicResource
  • No WrapPanel

I haven’t verified the above list yet – save that they gave me compilation errors. I easily found a replacement UniformGrid, but there are a few items on the list that may pose more of a problem.

The next step is to get some level of interaction working.

Developing for Windows Mobile – XAML for Win Forms

Many years ago (2004/5?) I was given the task of writing a XAML engine for System.Windows.Forms. It was a great experience and to do the job properly (I hope) it took quite some time. It had support for most of what’s available in WPF’s XAML – namespaces, markup extensions, attached properites (IExtenderProviders in WinForms speak), type converters, late bound binding, styles, triggers etc. plus a bunch of stuff that isn’t – #include, using parameterized constructors, simplified referencing etc.

In my Windows Mobile UI Framework the idea of having the capability of defining screens in XAML was kind of an afterthought. I had truly forgotten how painful it is to define UI’s programmatically. I’ve also never been a fan of form designers – I think they are slow, in-accurate and generate hard to maintain code/XAML. To this day I do 90% of my XAML using an XML editor (VS or Kaxaml).

So as per my last post I whipped up a very simplified XAML parser/renderer to use with my Mobile UI Framework. However, the latest control that I added to the framework was FormHost which allows a System.Windows.Forms control to be hosted within a DrawingElement (my UI base class). Of course when I say “hosted” the FormHost is really just acting as a placeholder so that the hosted control can be positioned during the render pass.

Here’s the code I had to add for FormHost:

using System;
using System.Drawing;
using System.Windows.Forms;
using Spencen.Mobile.UI.Primitives;
namespace Spencen.Mobile.UI.Controls
public class FormHost : DrawingContainer
private Control _hostControl;
public FormHost( IDrawingHost host ) : base( host )
_hostControl = host as Control;
if ( _hostControl == null )
throw new ArgumentException(
"FormHost must have an IDrawingHost that is a Windows.Forms.Control.", "host");
// By default we have no background or border Background = new SolidBrush( Color.Transparent ); Stroke = null; } public Control HostedControl { get; set; } public override bool SupportsRotation { get { return false; } } protected override void OnRender( GraphicsContext context ) { base.OnRender( context ); var transformedBounds = TransformedBounds( context ); if ( !_hostControl.Controls.Contains( HostedControl ) ) _hostControl.Controls.Add( HostedControl ); var newLocation = new Point( transformedBounds.Left, transformedBounds.Top ); if ( newLocation != HostedControl.Location ) HostedControl.Location = newLocation; var newSize = new Size( transformedBounds.Width + 1, transformedBounds.Height + 1); if ( newSize != HostedControl.Size ) HostedControl.Size = newSize; } } }

So pretty simple – but what was extra nice was the fact that it meant I could immediately declare my hosted System.Windows.Forms controls using XAML without any changes to the XAML parser/renderer at all.

<?xml version="1.0" encoding="utf-8" ?>

<DrawingPanel x:Name="container" DesiredSize="Unbound" Background="{null}">
<TextElement Text="Text" DesiredSize="150,60" AutoSize="True"/> 
<RectangleElement DesiredSize="50,80"/>
    <EllipseElement DesiredSize="40,70"/>
<RegularPolygonElement NumberOfSides="6" DesiredSize="80,80"/>
<RegularPolygonElement NumberOfSides="3" DesiredSize="90,70"/>
<RegularPolygonElement NumberOfSides="8" DesiredSize="80,80"/> <Star NumberOfPoints="5" DesiredSize="80,80"/> <!-- Just to spice things up - here's some WinForms controls - just don't expect them to rotate! --> <FormHost DesiredSize="240,40"> <FormHost.HostedControl> <WinForms:TextBox Text="Hello WinForms" Multiline="True" BackColor="240,255,240"/> </FormHost.HostedControl> </FormHost> <FormHost DesiredSize="240,80"> <FormHost.HostedControl> <WinFormsanel> <WinFormsanel.Controls> <WinForms:RadioButton Checked="True" Text="Is WinForms?" BackColor="255,255,223"
Dock="Top" Height="20"
/> <WinForms:RadioButton Checked="True" Text="Is MobileUI?" BackColor="255,255,223"
/> </WinFormsanel.Controls> </WinFormsanel> </FormHost.HostedControl> </FormHost> </DrawingPanel> </View>

MobileUI_Screenshot 5

Developing for Windows Mobile – Mobile XAML?

I’ve now included a “first cut” XAML parser (ultra simplistic) within v0.2 of my Mobile UI Framework.

Allows me to convert:

<?xml version="1.0" encoding="utf-8" ?>
<GradientRectangleElement DesiredSize="Unbound" StartColor="240,240,240" EndColor="200,80,0"/>
<TextElement DesiredSize="400,500" Foreground="200,200,200" Text="Demo" Angle="315" AutoSize="True" 
HorizontalAlignment="Center" VerticalAlignment="Center"
/> <DrawingPanel DesiredSize="Unbound" Background="{null}"> <DrawingPanel.LayoutEngine> <StackLayout Margin="8,4" Padding="4"/> </DrawingPanel.LayoutEngine> <ButtonBar Text="Animations" SecondaryText="Animate properties of graph primitives"
DesiredSize="UnboundAxis, 80" Background="{null}"
/> <ButtonBar Text="Trasitions" SecondaryText="Optimized bitmap animations"
DesiredSize="UnboundAxis, 80" Background="{null}"
/> <ButtonBar Text="Primitives" SecondaryText="Polygon, Ellipse, Image, Text"
DesiredSize="UnboundAxis, 80" Background="{null}"
/> <ButtonBar Text="Behaviours" SecondaryText="Drag with slide"
DesiredSize="UnboundAxis, 80" Background="{null}" Command="{Binding DragDemoCommand}"
/> <ButtonBar Text="Layout" SecondaryText="Stack, Wrap and Radial"
DesiredSize="UnboundAxis, 80" Background="{null}" Command="{Binding LayoutDemoCommand}"
/> </DrawingPanel> </DrawingPanel>


I was getting really sick of doing it the “old fashioned way”

So far I support simple value type converters (float, bool), pen and brush converters, size and padding converters, resource naming (x:Name), complex properties (DrawingPanel.LayoutEngine) and loading types from other CLR namespaces via XML namespace (xmlns:sysDrawing).