XDocument in Settings
I am trying 开发者_如何学Pythonto hand enter an XDocument
in the settings pane of VS2010 without success. The type is System.Xml.Linq.XDocument
The message I get is:
Cannot be converted to an instance of type 'System.Xml.Linq.XDocument'
Does anyone know a way around this?
ST
You can't create an XDocument
setting directly, because the XDocument
class doesn't meet the criteria used by the Settings to determine if a type can be used:
Application settings can be stored as any data type that is XML serializable or has a TypeConverter that implements ToString/FromString. The most common types are String, Integer, and Boolean, but you can also store values as Color, Object, or as a connection string.
XDocument
provides a way to create an XML document by parsing a string, but it's not a constructor, it's the static Load
method (which takes a TextWriter
, not a string). So it's not suited for use in the Settings.
But you can subclass it, and give the subclass a type converter. Fortunately, it's pretty easy to subclass XDocument
with a type converter. First, create a subclass:
[TypeConverter(typeof(MyXDocumentTypeConverter))]
public class MyXDocument : XDocument
{
}
That class uses this TypeConverter
:
public class MyXDocumentTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return (sourceType == typeof (string));
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
MyXDocument d = new MyXDocument();
d.Add(XDocument.Load(new StringReader((string) value)).Elements().First());
return d;
}
return null;
}
}
Once you have this set up, you can write code like this:
MyXDocument d = "<foo/>";
and the string <foo/>
will get passed into the type converter and parsed (via Load
) into an XDocument
, whose top-level element then gets added to the MyXDocument
. This is the same assignment that the auto-generated code in Settings.Designer.cs
uses:
return ((global::XmlSettingsDemo.MyXDocument)(this["Setting"]));
Now you can go into your Settings dialog and create a setting of this type. You can't navigate to the type in the Type dialog; you have to manually enter the full name of the type (XmlSettingsDemo.MyXDocument
was the name of mine).
精彩评论