问题
Passing a string to the DependencyProperty
of a control that takes a DateTime
does not seem to be allowed:
Cannot assign text value '00:00:00' into property 'StartTime' of type 'DateTime'
Is it just me or shouldn't this be possible? The workaround I suppose is to provide a IValueConverter to convert strings to DateTime objects. For Scheduler/Calender like controls this is a little annoying.
Shed some light?
回答1:
TypeConverter
isn't available in WinRT and while the platform seems to have some built in conversions for many UI types - this implicit conversion is not one of those. You have a few options though.
- As you mentioned - you can use a value converter
- You can make sure your
DateTime
property is bound to aDateTime
view model property. - Define your property as type
String
and do the conversions inside of your control - if you would typically initialize that property with a XAML string. It would also be worth it to append 'String' to the name of the property to make it clear that it's a string - e.g. 'StartDateString'. - If you would like to use your control both with
DateTime
andString
types - you could have properties of both types and synchronize them internally, making sure to prevent reentrancy in property change handlers. - Declare the property as type
Object
and detect what type the values being set are to either set aDateTime
value directly, convert fromString
or other types (DateTimeOffset
,TimeSpan
, ...?) or throw for unsupported values.
Unfortunately until the Windows platform teams add support for TypeConverter
attribute - you don't have a pretty solution.
来源:https://stackoverflow.com/questions/22041730/datetime-xaml-winrt