开发者

XAML test data - designer can convert types but runtime cannot

开发者 https://www.devze.com 2023-01-11 06:45 出处:网络
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:

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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消