开发者

Undefined Enum & WPF ComboBox & WCF Serialization

开发者 https://www.devze.com 2023-01-17 11:46 出处:网络
I\'m having problems finding a general solution to deal with Enum fields on WPF and WCF, I need a little bit of help. Let\'s explain with an example:

I'm having problems finding a general solution to deal with Enum fields on WPF and WCF, I need a little bit of help. Let's explain with an example:

When creating a person with a Sex enum value [Male, Female] I see three posibilites:

  1. Male is default -> There are two posibilities but one is default. No problems binding the ComboBox.SelectedValue and no problem with WCF serialization, as long as no female feels ofended :)

  2. ((Sex)(3)) Undefined value is default -> There are two posibilities but at the begining the user is forced to pick one. ComboBox.SelectedValue correctly sets SelectedIndex = -1, but WCF throws: Enum value '3' is invalid for type 'Sex' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.

  3. Sex property is nullable -> Its optional to set the Sex and u can even unset it once u pick one.

Unfortunately, case 2 is the most common one but we don't see a simple way to deal with it without making hacks like:

  • Define 'Unknown' value for Sex, this value is not valid for the entity, I would consider if it will not be the most common scenario.
  • Mark the enum as [Flags] so WCF can codify "Male,Female" as unknown.
  • Decorate the sex property with something like [ComboHintUnkwnownOnNew].
  • Set SelectedIndex=-1 while keeping the binding some how in WPF.

I know is a 开发者_Python百科thought design decission, not a concrete problem, but I would appreciate some help.


How about defining a client side enum (with -1 for undefined) for the view only and then depending on the sex selected create appropriate WCF proxy enum and then send this to the service. So do not databind directly to the WCF proxy classes. It is quite valid to create client only models and convert to valid entities (WCF proxy classes). You can use something like automapper to do this easily.


So far we have found the following solution:

Sex Sex {get; set;}  //Default Male

Sex? Sex {get; set;}  //Optional field, none is available in the combobox

[NotNullValidator]
Sex? Sex {get; set;}  //Default is null, so SelectedIndex=-1 and can be sent via WCF, but the combo does not have the 'none' option and once one Sex is selected u can not turn back.  

Sorry for making such an abstract and hard to answer question

0

精彩评论

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