views:

65

answers:

2

I am designing a user control to display a note. So I have a NoteViewModel. In my designer I want to have a test note. So I have the following in my XAML:

<UserControl.Resources>
    <local:NoteViewModel x:Key="ViewModel" d:IsDataSource="True">
        <local:NoteViewModel.Note>
            <localweb:Note
                NoteID="1"
                CreatedBy="Some Guy"
                CreatedDate="2010-01-01 8:00 AM"
                Category="Some Category"
                NoteText="Some Text"
                />
        </local:NoteViewModel.Note>
    </local:NoteViewModel>
</UserControl.Resources>

This works great at design time. But at runtime I get errors about not being able to convert "1" to an Int32, and not being able to convert "2010-01-01 8:00 AM" to a DateTime. Why is the designer able to deal with this but not the runtime? How should I change my XAML so that the designer can show the test note but the runtime doesn't crash?

A: 

The designer is often more forgiving than the standard runtime Xaml parser.

I can't understand why it can't convert "1" to Int32 since int is one of the few primitive types that parse in Xaml natively. You would need to decorate your CreatedDate property with TypeConverterAttribute :-

 [TypeConverterAttribute(typeof(DateTimeTypeConverter))]
 public CreatedDate { get; set; }

without this the xaml parser doesn't really know what to do with the date. It gets worse in that the designer will use the standard UI culture to determine how to parse the date whereas Xaml will use often use something different. I've found this particular problem quite intractable.

AnthonyWJones
DateTimeTypeConverter is in System.Windows.Controls. Are you saying I'd have to reference that in my business logic tier in order to decorate the class? That seems...unfortunate.
jkohlhepp
@jkohilhepp: `TypeConverterAttribute` has another constructor which takes the name of the type to use as a converter, so you could use this alternative to avoid having an additional reference.
AnthonyWJones
+1  A: 

Don't know why it is happening, but to fix the problem with the Int, you could try to specify the type of the value for NoteID:

    <localweb:Note xmlns:sys="clr-namespace:System;assembly=mscorelib" ...>
        <localweb:Note.NoteID><sys:Int32>1</sys:Int32></localweb:Note.NoteID>
    </localweb:Note>

A bit long, but should probably work.

Pablo Montilla
Well it has been long enough where I don't think I can recreate the exact scenario to quickly test this. But since this seems like a good suggestion I'll give ya the bounty. :-) Thanks.
jkohlhepp
Thank you, that was my first bounty. :)
Pablo Montilla