public void TestFixtureSetUp() { if (_dummyCulture == null) throw new Exception("Error setting up test - dummyCulture should not be NULL"); if (CultureInfo.InvariantCulture.Equals(_dummyCulture)) throw new Exception("Error setting up test - dummyCulture should not be invariant"); if (_dummyCulture2 == null) throw new Exception("Error setting up test - dummyCulture2 should not be NULL"); if (CultureInfo.InvariantCulture.Equals(_dummyCulture2)) throw new Exception("Error setting up test - dummyCulture2 should not be invariant"); if (_dummyCulture2.Equals(_dummyCulture)) throw new Exception("Error setting up test - dummyCulture2 should not be the same as dummyCulture"); // for testing purposes, set up the converter for a specific culture to have a custom mapping // normally, you would use TypeDescriptor.GetConverter, but we want to keep the test appdomain clean of these testing mods XMouseButtonsConverter converter = new XMouseButtonsConverter(_dummyCulture); IDictionary<XMouseButtons, string> relocalizedNames = new Dictionary<XMouseButtons, string>(); relocalizedNames[XMouseButtons.Left] = "LMouse"; relocalizedNames[XMouseButtons.Right] = "RMouse"; relocalizedNames[XMouseButtons.Middle] = "Mouse3"; relocalizedNames[XMouseButtons.XButton1] = "Mouse4"; relocalizedNames[XMouseButtons.XButton2] = XMouseButtonsConverter.ButtonSeparator.ToString(); converter.LocalizedNames = relocalizedNames; _converter = converter; }
/// <summary> /// This method retrieves a set of CDSAttribute from a class. /// </summary> /// <param name="data">The class to examine.</param> /// <param name="conv">A converter function to turn the value in to a string.</param> /// <returns>Returns an enumerable collection of attributes and values.</returns> public static IEnumerable<KeyValuePair<CDSAttributeAttribute, string>> CDSAttributesRetrieve( this IXimuraContent data, TypeConverter conv) { List<KeyValuePair<PropertyInfo, CDSAttributeAttribute>> attrList = AH.GetPropertyAttributes<CDSAttributeAttribute>(data.GetType()); foreach (KeyValuePair<PropertyInfo, CDSAttributeAttribute> reference in attrList) { PropertyInfo pi = reference.Key; if (pi.PropertyType == typeof(string)) { yield return new KeyValuePair<CDSAttributeAttribute, string>( reference.Value, pi.GetValue(data, null) as string); } else if (pi.PropertyType == typeof(IEnumerable<string>)) { IEnumerable<string> enumerator = pi.GetValue(data, null) as IEnumerable<string>; foreach (string value in enumerator) yield return new KeyValuePair<CDSAttributeAttribute, string>( reference.Value, value); } else if (conv != null && conv.CanConvertFrom(pi.PropertyType)) { yield return new KeyValuePair<CDSAttributeAttribute, string>( reference.Value, conv.ConvertToString(pi.GetValue(data, null))); } } }
public LocalizedPropertyDescriptor(PropertyDescriptor basePropertyDescriptor) : base(basePropertyDescriptor) { this.localizedName = string.Empty; this.localizedDescription = string.Empty; this.localizedCategory = string.Empty; this.customTypeConverter = null; LocalizedPropertyAttribute attribute = null; foreach (Attribute attribute2 in basePropertyDescriptor.Attributes) { attribute = attribute2 as LocalizedPropertyAttribute; if (attribute != null) { break; } } if (attribute != null) { this.localizedName = attribute.Name; this.localizedDescription = attribute.Description; this.localizedCategory = attribute.Category; } else { this.localizedName = basePropertyDescriptor.Name; this.localizedDescription = basePropertyDescriptor.Description; this.localizedCategory = basePropertyDescriptor.Category; } this.basePropertyDescriptor = basePropertyDescriptor; if (basePropertyDescriptor.PropertyType == typeof(bool)) { this.customTypeConverter = new BooleanTypeConverter(); } }
/// <summary> /// </summary> protected T ReadSetting <T>(string settingName, T defaultValue) { Hashtable settings = _controller.GetTabModuleSettings(_tabModuleId); T ret = default(T); if (settings.ContainsKey(settingName)) { System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)); try { ret = (T)tc.ConvertFrom(settings[settingName]); } catch { ret = defaultValue; } } else { ret = defaultValue; } return(ret); }
public override object ParseFormattedValue( object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter) { int result; if (int.TryParse(formattedValue.ToString(), NumberStyles.HexNumber, null, out result)) { //Hex number return base.ParseFormattedValue( "0x" + formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter ); } return base.ParseFormattedValue( formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter ); }
private static object DoConversion(object value, Type toType, CultureInfo culture) { if ((value is IConvertible) || (value == null)) { try { return(System.Convert.ChangeType(value, toType, culture)); } catch (Exception) { return(DependencyProperty.UnsetValue); } } else { System.ComponentModel.TypeConverter typeConverter = TypeDescriptor.GetConverter(value); if (typeConverter.CanConvertTo(toType)) { return(typeConverter.ConvertTo(null, culture, value, toType)); } } return(DependencyProperty.UnsetValue); }
public override bool Execute() { try { try { codeDomProvider = CodeDomProvider.CreateProvider(Language); } catch (ConfigurationErrorsException) { LogError(classNameLineNumber, 1, "CodeDom provider for language '" + Language + "' not found."); return false; } typeAttributesConverter = codeDomProvider.GetConverter(typeof(TypeAttributes)); if (!ParseInput()) { return false; } if (lambdas.Count == 0) { OutputFileName = null; return true; } if (className == null) { LogError(classNameLineNumber, 1501, "x:Class not found on root element."); return false; } if (!className.Contains(".")) { LogError(classNameLineNumber, 1502, "x:Class does not include namespace name."); return false; } return GenerateOutput(); } catch (Exception ex) { LogError(null, 0, 0, ex.Message); return false; } }
protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e) { System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Point)); base.OnMouseMove(e); if (TopCap) { Parent.Location = MousePosition - new Size(MouseP); } if (Sizable & Drag & SizeCap) { MouseP = e.Location; Parent.Size = new Size(MouseP); Invalidate(); } if (Sizable & new Rectangle(Width - 10, Height - 10, 10, 10).Contains(e.Location)) { Cursor = Cursors.SizeNWSE; } else { Cursor = Cursors.Arrow; } }
private static bool InnerConvertObjectToType(object obj, Type type, bool throwOnError, out object convertedObject) { Type originalType = obj.GetType(); OriginalTypeConverter converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(originalType)) { try { convertedObject = converter.ConvertFrom(null, CultureInfo.InvariantCulture, obj); return(true); } catch { if (throwOnError) { throw; } convertedObject = null; return(false); } } if (converter.CanConvertFrom(typeof(string)) && !(obj is DateTime)) { try { string text = TypeDescriptor.GetConverter(originalType).ConvertToInvariantString(obj); convertedObject = converter.ConvertFromInvariantString(text); return(true); } catch { if (throwOnError) { throw; } convertedObject = null; return(false); } } if (type.IsInstanceOfType(obj)) { convertedObject = obj; return(true); } if (throwOnError) { throw new InvalidOperationException(); } convertedObject = null; return(false); }
// ======================================================================== // Methods #region === Methods /// <summary> /// Gets the formatted value of the cell's data. /// </summary> /// <returns> /// The value. /// </returns> /// <param name = "value">The value to be formatted. </param> /// <param name = "rowIndex">The index of the cell's parent row. </param> /// <param name = "cellStyle">The <see cref = "T:System.Windows.Forms.DataGridViewCellStyle" /> in effect for the cell.</param> /// <param name = "valueTypeConverter">A <see cref = "T:System.ComponentModel.TypeConverter" /> associated with the value type that provides custom conversion to the formatted value type, or null if no such custom conversion is needed.</param> /// <param name = "formattedValueTypeConverter">A <see cref = "T:System.ComponentModel.TypeConverter" /> associated with the formatted value type that provides custom conversion from the value type, or null if no such custom conversion is needed.</param> /// <param name = "context">A bitwise combination of <see cref = "T:System.Windows.Forms.DataGridViewDataErrorContexts" /> values describing the context in which the formatted value is needed.</param> /// <exception cref = "T:System.Exception">Formatting failed and either there is no handler for the <see cref = "E:System.Windows.Forms.DataGridView.DataError" /> event of the <see cref = "T:System.Windows.Forms.DataGridView" /> control or the handler set the <see cref = "P:System.Windows.Forms.DataGridViewDataErrorEventArgs.ThrowException" /> property to true. The exception object can typically be cast to type <see cref = "T:System.FormatException" /> for type conversion errors or to type <see cref = "T:System.ArgumentException" /> if <paramref name = "value" /> cannot be found in the <see cref = "P:System.Windows.Forms.DataGridViewComboBoxCell.DataSource" /> or the <see cref = "P:System.Windows.Forms.DataGridViewComboBoxCell.Items" /> collection. </exception> protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { return value; }
public PropertyDescriptorCollection AddProperty(PropertyDescriptorCollection pdc, string propertyName, Type propertyType, TypeConverter converter, Attribute[] attributes) { List<PropertyDescriptor> properties = new List<PropertyDescriptor>(pdc.Count); for (int i = 0; i < pdc.Count; i++) { PropertyDescriptor pd = pdc[i]; if (pd.Name != propertyName) { properties.Add(pd); } } InstanceSavePropertyDescriptor ppd = new InstanceSavePropertyDescriptor( propertyName, propertyType, attributes); ppd.TypeConverter = converter; properties.Add(ppd); //PropertyDescriptor propertyDescriptor; return new PropertyDescriptorCollection(properties.ToArray()); }
/// <inheritdoc /> public override bool TryConvert(object value, Type destinationType, out object result, ConversionArgs args) { System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(destinationType); if (converter.GetType() != typeof(System.ComponentModel.TypeConverter) && converter.CanConvertFrom(value.GetType())) { try { result = converter.ConvertFrom(null, args.Culture, value); return(true); } catch { } } converter = TypeDescriptor.GetConverter(value.GetType()); if (converter.GetType() != typeof(System.ComponentModel.TypeConverter) && converter.CanConvertTo(destinationType)) { try { result = converter.ConvertTo(null, args.Culture, value, destinationType); return(true); } catch { } } result = null; return(false); }
protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { string strValue = String.Empty; if (value != null && value.ToString() != String.Empty) { string[] ids = value.ToString().Split('.'); DataEntity dataEntity = ServiceUnity.DataEntityComponentService.GetDataEntity(ids[0]); if (dataEntity != null) { strValue = dataEntity.Name; if (ids.Length == 2) { DataItemEntity item = dataEntity.Items.GetEntityById(ids[1]); if (item != null) { strValue += "." + item.Name; } else { strValue = String.Empty; } } } } else { strValue = String.Empty; } return(base.GetFormattedValue(strValue, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context)); }
protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { isVisualStyled = VisualStyleInformation.IsEnabledByUser & VisualStyleInformation.IsSupportedByOS; if (value == null) { return emptyImage; } float percentage = (float)((int)value); if (percentage == 0) return emptyImage; else { contentGraphics.Clear(Color.Transparent); float drawedPercentage = percentage > 100 ? 100 : percentage; if (isVisualStyled) { bigProgressRect.Width = (int)(66 * drawedPercentage / 100.0f); ProgressBarRenderer.DrawHorizontalBar(contentGraphics, bigBorderRect); ProgressBarRenderer.DrawHorizontalChunks(contentGraphics, bigProgressRect); } else { progressRect.Width = (int)(66 * drawedPercentage / 100.0f); contentGraphics.DrawRectangle(blackPen, borderRect); contentGraphics.FillRectangle(lightGreenBrush, progressRect); } contentGraphics.DrawString(percentage.ToString("0.00") + "%", this.DataGridView.Font, foreColor, 10, 5); } return contentImage; }
private object GetValue(DateTime dateTime, Type type, TypeConverter converter) { if (type.IsAssignableFrom(typeof(DateTime))) return dateTime; else return converter.ConvertFrom(dateTime); }
public RightHandSideExpressionVisitor(Type compareType) { _compareType = compareType; _toConverter = TypeDescriptor.GetConverter(_compareType); _value = () => { throw new InvalidOperationException("No match was found"); }; }
public LocalizedPropertyDescriptor(PropertyDescriptor basePropertyDescriptor) : base(basePropertyDescriptor) { LocalizedPropertyAttribute localizedPropertyAttribute = null; foreach (Attribute attr in basePropertyDescriptor.Attributes) { localizedPropertyAttribute = attr as LocalizedPropertyAttribute; if (localizedPropertyAttribute != null) { break; } } if (localizedPropertyAttribute != null) { localizedName = localizedPropertyAttribute.Name; localizedDescription = localizedPropertyAttribute.Description; localizedCategory = localizedPropertyAttribute.Category; } else { localizedName = basePropertyDescriptor.Name; localizedDescription = basePropertyDescriptor.Description; localizedCategory = basePropertyDescriptor.Category; } this.basePropertyDescriptor = basePropertyDescriptor; // "Booleans" get a localized type converter if (basePropertyDescriptor.PropertyType == typeof(System.Boolean)) { customTypeConverter = new BooleanTypeConverter(); } }
public ConfigurationProperty ( string name, Type type, object default_value, TypeConverter converter, ConfigurationValidatorBase validation, ConfigurationPropertyOptions flags) : this (name, type, default_value, converter, validation, flags, null) { }
protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { object returnVal = String.Empty; if (value != null) { if (value.GetType() == typeof(byte[])) returnVal = BitConverter.ToString((byte[])value); else if (value.GetType() == typeof(byte)) returnVal = BitConverter.ToString(new byte[] { (byte)value }); else if (value.GetType() == typeof(int)) returnVal = BitConverter.ToString(BitConverter.GetBytes(((int)value)),0); else if (value.GetType() == typeof(uint)) returnVal = BitConverter.ToString(BitConverter.GetBytes(((uint)value)), 0); else if (value.GetType() == typeof(short)) returnVal = BitConverter.ToString(BitConverter.GetBytes(((short)value)), 0); else if (value.GetType() == typeof(ushort)) returnVal = BitConverter.ToString(BitConverter.GetBytes(((ushort)value)), 0); } return returnVal; }
/* * static void ReLayout(Control parent_control) * { * foreach (Control control in parent_control.Controls) * { * ReLayout(control); * * control.ResumeLayout(false); * control.PerformLayout(); * } * * parent_control.ResumeLayout(false); * }*/ /// <summary> /// 保存字体设置信息到配置参数存储 /// </summary> public void SaveFontSetting() { if (this.MainForm != null && this.MainForm.AppInfo != null) { { // Create the FontConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Font)); string strFontString = converter.ConvertToString(this.Font); this.MainForm.AppInfo.SetString( this.FormName, "default_font", strFontString); } { // Create the ColorConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Color)); string strFontColor = converter.ConvertToString(this.ForeColor); MainForm.AppInfo.SetString( this.FormName, "default_font_color", strFontColor); } } }
public void SetUp () { Assembly a = typeof (LogConverter).Assembly; Type type = a.GetType ("System.Diagnostics.Design.StringValueConverter"); Assert.IsNotNull (type); converter = (TypeConverter) Activator.CreateInstance (type); }
private DateTime GetDateTime(object value, TypeConverter converter) { if (typeof(DateTime).IsAssignableFrom(value.GetType())) return (DateTime) value; else return (DateTime) converter.ConvertTo(value, typeof(DateTime)); }
public bool IsForType(TypeConverter converter) { Contract.Requires<ArgumentNullException>(converter != null); Type currentConverterType = this.typeConverter.GetType(); Type paramConverterType = converter.GetType(); return paramConverterType.IsAssignableFrom(currentConverterType); }
public HotkeyEditControl() { InitializeComponent(); InitializeDropdown(); converter = TypeDescriptor.GetConverter(typeof(Keys)); }
/// <summary> /// 转换简单类型 /// </summary> /// <param name="value"></param> /// <param name="type"></param> /// <returns></returns> private static object ConvertObj(object value, Type type) { object returnValue; if ((value == null) || type.IsInstanceOfType(value)) { return(value); } string str = value as string; if ((str != null) && (str.Length == 0)) { return(null); } System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type); bool flag = converter.CanConvertFrom(value.GetType()); if (!flag) { converter = TypeDescriptor.GetConverter(value.GetType()); } if (!flag && !converter.CanConvertTo(type)) { throw new InvalidOperationException("无法转换成类型:" + value.ToString() + "==>" + type); } try { returnValue = flag ? converter.ConvertFrom(null, null, value) : converter.ConvertTo(null, null, value, type); } catch (Exception e) { throw new InvalidOperationException("类型转换出错:" + value.ToString() + "==>" + type, e); } return(returnValue); }
public void TestFixtureSetUp() { if (_dummyCulture == null) throw new Exception("Error setting up test - dummyCulture should not be NULL"); if (CultureInfo.InvariantCulture.Equals(_dummyCulture)) throw new Exception("Error setting up test - dummyCulture should not be invariant"); if (_dummyCulture2 == null) throw new Exception("Error setting up test - dummyCulture2 should not be NULL"); if (CultureInfo.InvariantCulture.Equals(_dummyCulture2)) throw new Exception("Error setting up test - dummyCulture2 should not be invariant"); if (_dummyCulture2.Equals(_dummyCulture)) throw new Exception("Error setting up test - dummyCulture2 should not be the same as dummyCulture"); // for testing purposes, set up the converter for a specific culture to have the Enum.ToString() mapping // normally, you would use TypeDescriptor.GetConverter, but we want to keep the test appdomain clean of these testing mods XKeysConverter converter = new XKeysConverter(_dummyCulture); IDictionary<XKeys, string> relocalizedKeyNames = new Dictionary<XKeys, string>(); foreach (KeyValuePair<XKeys, string> pair in converter.LocalizedKeyNames) relocalizedKeyNames.Add(pair.Key, Enum.GetName(typeof (XKeys), pair.Key)); relocalizedKeyNames[XKeys.Control] = "Control"; // Enum.ToString() treats this as Control+None relocalizedKeyNames[XKeys.Shift] = "Shift"; // Enum.ToString() treats this as Shift+None relocalizedKeyNames[XKeys.Alt] = "Alt"; // Enum.ToString() treats this as Alt+None relocalizedKeyNames[XKeys.OemPlus] = XKeysConverter.KeySeparator.ToString(); // for special case test converter.LocalizedKeyNames = relocalizedKeyNames; _converter = converter; }
public OptionConfigurationPropertyAttribute(string name, Type type, object defaultValue, OptionConfigurationPropertyBehavior behavior, TypeConverter converter) { _name = name == null ? string.Empty : name.Trim(); _type = type; _defaultValue = defaultValue; _behavior = behavior; _converter = converter; }
public ConfigurationProperty(String name, Type type, Object defaultValue, TypeConverter typeConverter, ConfigurationValidatorBase validator, ConfigurationPropertyOptions options) : this(name, type, defaultValue, typeConverter, validator, options, null) { }
private static string GetTypeConverterId(System.ComponentModel.TypeConverter typeConverter) { if (typeConverter == null) { return(string.Empty); } return(typeConverter.GetType().FullName); }
protected DefaultValueConverter(TypeConverter typeConverter, Type sourceType, Type targetType, bool shouldConvertFrom, bool shouldConvertTo) { this.typeConverter = typeConverter; this.sourceType = sourceType; this.targetType = targetType; this.shouldConvertFrom = shouldConvertFrom; this.shouldConvertTo = shouldConvertTo; }
protected override void FillAttributes(IList attributeList) { this.converter = null; this.editors = null; this.editorTypes = null; this.editorCount = 0; base.FillAttributes(attributeList); }
protected override object GetFormattedValue(object value, int rowIndex, ref System.Windows.Forms.DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, System.Windows.Forms.DataGridViewDataErrorContexts context) { if (value != null) { return TypeDescriptor.GetConverter(value).ConvertToString(value); } return ""; }
/// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="pi"></param> /// <param name="obj"></param> public ConfigVariable ( string prefix, string name, PropertyInfo pi, object obj ) { Prefix = prefix; Name = name; Property = pi; Object = obj; converter = TypeDescriptor.GetConverter( Property.PropertyType ); }
public StringConvertibleType(TypeConverter converter, Type sourceType) { if (converter == null) throw new ArgumentNullException(nameof(converter)); if (sourceType == null) throw new ArgumentNullException(nameof(sourceType)); this.converter = converter; this.sourceType = sourceType; }
/// <summary> /// Initializes a new instance of the <see cref="NameableConverter"/> class. /// </summary> /// <param name="type">The type.</param> /// <exception cref="System.ArgumentException">NameableConverterBadCtorArg;type</exception> public NameableConverter(Type type) { _nameableType = type; _simpleType = Nullable.GetUnderlyingType(type); if (_simpleType == null) throw new ArgumentException("NameableConverterBadCtorArg", "type"); _simpleTypeConverter = TypeDescriptor.GetConverter(_simpleType); }
public ShortcutKeysUI(ShortcutKeysEditor editor) { this.editor = editor; this.keysConverter = null; this.End(); this.InitializeComponent(); this.AdjustSize(); }
protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { if (value == null) value = 0; int progressVal = (int)value; if (progressVal > maxVal) progressVal = maxVal; if (progressVal < minVal) progressVal = minVal; Bitmap bmp = new Bitmap(OwningColumn.Width - margin, OwningRow.Height - margin); Bitmap bmptxt = new Bitmap(OwningColumn.Width, OwningRow.Height); pb.Height = bmp.Height; pb.Width = bmp.Width; pb.BackColor = System.Drawing.Color.Transparent; pb.BackgroundColor = System.Drawing.Color.FromArgb(((System.Byte)(100)), ((System.Byte)(201)), ((System.Byte)(201)), ((System.Byte)(201))); pb.StartColor = this.startColor; pb.EndColor = this.endColor; //pb.HighlightColor = System.Drawing.Color.Orange; pb.TabIndex = 0; pb.Value = progressVal; pb.Update(); pb.Invalidate(); lbl.AutoSize = false; lbl.TextAlign = ContentAlignment.MiddleCenter; lbl.Height = bmptxt.Height; lbl.Width = bmptxt.Width; if (!this.Selected) { lbl.ForeColor = cellStyle.ForeColor; lbl.BackColor = cellStyle.BackColor; } else { lbl.ForeColor = cellStyle.SelectionForeColor; lbl.BackColor = cellStyle.SelectionBackColor; } pb.DrawToBitmap(bmp, pb.ClientRectangle); lbl.Text = String.Format("{0}%", progressVal); lbl.Image = bmp; lbl.ImageAlign = ContentAlignment.MiddleCenter; lbl.DrawToBitmap(bmptxt, lbl.ClientRectangle); return bmptxt; }
public TypeConverterWrapper(TypeConverter converter, Type resultType, Action<object, object> objectGenerator = null) { this.typeConverter = converter; this.objectGenerator = objectGenerator; MethodInfo method = typeof(Enumerable).GetMethod("OfType"); MethodInfo generic = method.MakeGenericMethod(new Type[] { resultType }); ConvertEnumerable = o => generic.Invoke(null, new[] { o }); }
public SimpleTypeModelBinder(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } _typeConverter = TypeDescriptor.GetConverter(type); }
/// <summary> ///构造函数 /// </summary> /// <exception cref="InvalidOperationException">类型不存在类型转换器 " + typeof(T).FullName</exception> public GenericListTypeConverter() { typeConverter = SysComponentModel.TypeDescriptor.GetConverter(typeof(T)); if (typeConverter == null) { throw new InvalidOperationException("类型不存在类型转换器 " + typeof(T).FullName); } }
void radListControl1_VisualItemFormatting(object sender, Telerik.WinControls.UI.VisualItemFormattingEventArgs args) { RadListVisualItem item = args.VisualItem; int rowIndex = item.Data.RowIndex; System.ComponentModel.TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(Color)); item.DrawFill = true; item.BackColor = (Color)typeConverter.ConvertFromString(null, CultureInfo.InvariantCulture, bgColors[rowIndex % 7]); item.GradientStyle = Telerik.WinControls.GradientStyles.Solid; }
void TypeConverters() { System.ComponentModel.TypeConverter testConverter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(System.Drawing.Color)); System.Drawing.Color result = (System.Drawing.Color)testConverter.ConvertFrom("cyan"); var alt = System.Drawing.Color.FromName("cyan"); Console.WriteLine(result); Console.WriteLine(alt == result); }
/// <summary> /// Gets the localized description for given value and specified CultureInfo. /// </summary> /// <param name="enumValue">The given value.</param> /// <param name="ci">The CultureInfo.</param> /// <returns>The localized value.</returns> public static string GetLocalizedDescription(this Enum enumValue, CultureInfo ci) { if (enumValue != null) { System.ComponentModel.TypeConverter tc = TypeDescriptor.GetConverter(enumValue.GetType()); return(tc != null ? tc.ConvertToString(null, ci, enumValue) : enumValue.ToString()); } return(string.Empty); }
protected override void OnLoadingValueType() { base.OnLoadingValueType(); if (ValueType != null) { TypeConverter = System.ComponentModel.TypeDescriptor.GetConverter(ValueType); } else { TypeConverter = null; } }
public static System.Drawing.Font StringToFont(string fontString) { try { System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(System.Drawing.Font)); return((System.Drawing.Font)converter.ConvertFromString(fontString)); } catch { return(null); } }
/// <summary> /// 构造函数 /// </summary> /// <exception cref="InvalidOperationException"> /// 类型不存在类型转换器" + typeof(K).FullName /// or /// 类型不存在类型转换器" + typeof(V).FullName /// </exception> public GenericDictionaryTypeConverter() { typeConverterKey = TypeDescriptor.GetConverter(typeof(K)); if (typeConverterKey == null) { throw new InvalidOperationException("类型不存在类型转换器" + typeof(K).FullName); } typeConverterValue = TypeDescriptor.GetConverter(typeof(V)); if (typeConverterValue == null) { throw new InvalidOperationException("类型不存在类型转换器" + typeof(V).FullName); } }
//</snippet1> // The following code example demonstrates how to use the // ColorConverter.ConvertToString method. This example // is designed to be used with Windows Forms. Paste this code // into a form and call the ShowColorConverter method when // handling the form's Paint event, passing e as PaintEventArgs. //<snippet2> private void ShowColorConverter(PaintEventArgs e) { Color myColor = Color.PaleVioletRed; // Create the ColorConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(myColor); string colorAsString = converter.ConvertToString(Color.PaleVioletRed); e.Graphics.DrawString(colorAsString, this.Font, Brushes.PaleVioletRed, 50.0F, 50.0F); }
//</snippet2> // The following code example demonstrates how to use the // ConvertToInvariantString and ConvertToString methods. // This example is designed to be used with Windows Forms. // Paste this code into a form and call the ShowFontStringConversion // method when handling the form's Paint event, passing e // as PaintEventArgs. //<snippet3> private void ShowFontStringConversion(PaintEventArgs e) { // Create the FontConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Font)); Font font1 = (Font)converter.ConvertFromString("Arial, 12pt"); string fontName1 = converter.ConvertToInvariantString(font1); string fontName2 = converter.ConvertToString(font1); e.Graphics.DrawString(fontName1, font1, Brushes.Red, 10, 10); e.Graphics.DrawString(fontName2, font1, Brushes.Blue, 10, 30); }
// The following code example demonstrates how to use the // PointConverter.ConvertFromString and the Point.op_Subtraction // methods. This example is designed to be used with Windows // Forms. Paste this code into a form and call the // ShowPointConverter method when handling the form's Paint // event, passing e as PaintEventArgs. //<snippet1> private void ShowPointConverter(PaintEventArgs e) { // Create the PointConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Point)); Point point1 = (Point)converter.ConvertFromString("200, 200"); // Use the subtraction operator to get a second point. Point point2 = point1 - new Size(190, 190); // Draw a line between the two points. e.Graphics.DrawLine(Pens.Black, point1, point2); }
public void test1() { Rectangle rect = new Rectangle(10, 12, 14, 16); // Wrong System.ComponentModel.TypeConverter baseConverter = new System.ComponentModel.TypeConverter(); string sample1 = baseConverter.ConvertToString(rect); // Right System.ComponentModel.TypeConverter rectSpecificConverter = TypeDescriptor.GetConverter(rect); string sample2 = rectSpecificConverter.ConvertToString(rect); log.DebugFormat("From new TypeConverter() {0}\r\n", sample1); log.DebugFormat("From TypeDescriptor.GetConverter() {0}\r\n", sample2); log.DebugFormat("From rect.ToString() {0}\r\n", rect.ToString()); }
/// <summary> /// 从配置参数存储中装载字体设置信息 /// </summary> public void LoadFontSetting() { if (this.MainForm == null) { return; } if (this.MainForm != null && this.MainForm.AppInfo != null) { string strFontString = MainForm.AppInfo.GetString( this.FormName, "default_font", ""); // "Arial Unicode MS, 12pt" if (String.IsNullOrEmpty(strFontString) == false) { // Create the FontConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Font)); this.Font = (Font)converter.ConvertFromString(strFontString); } else { // 沿用系统的缺省字体 if (this.MainForm != null) { MainForm.SetControlFont(this, this.MainForm.DefaultFont); } } string strFontColor = MainForm.AppInfo.GetString( this.FormName, "default_font_color", ""); if (String.IsNullOrEmpty(strFontColor) == false) { // Create the ColorConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Color)); this.ForeColor = (Color)converter.ConvertFromString(strFontColor); } this.PerformLayout(); } }
//------------------------------------------------------------------------------------------------- public static object ConvertType(string value, Type type) { if (type.IsEnum) { return(Enum.Parse(type, value)); } System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter != null && converter.CanConvertFrom(value.GetType())) { return(converter.ConvertFrom(value)); } else { return(Convert.ChangeType(value, type)); } }
public static T ConvertType <T>(string value) { if (typeof(T).IsEnum) { return((T)Enum.Parse(typeof(T), value)); } System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); if (converter != null && converter.CanConvertFrom(value.GetType())) { return((T)converter.ConvertFrom(value)); } else { return((T)Convert.ChangeType(value, typeof(T))); } }
// this and next method taken from // http://stackoverflow.com/questions/1940127/how-to-xmlserialize-system-drawing-font-class public static string FontToString(System.Drawing.Font font) { if (font == null) { return(null); } try { System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(System.Drawing.Font)); return(converter.ConvertToString(font)); } catch { return(null); } }
private static void Label_set(Label l, Color c, int x, int y, int w, int h) { System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Font)); Font f = (Font)converter.ConvertFromString("Cambria, 18pt, style=Bold, Italic"); l.Font = f; l.BackColor = Color.Black; l.Visible = false; l.ForeColor = c; l.Top = x; l.Left = y; l.Width = w; l.Height = h; }
private static object ConvertSimpleType(CultureInfo culture, object value, Type destinationType) { if (value == null || destinationType.IsInstanceOfType(value)) { return(value); } // if this is a user-input value but the user didn't type anything, return no value string valueAsString = value as string; if (valueAsString != null && valueAsString.Trim().Length == 0) { return(null); } //modified by Yang Li //TypeConverter converter = TypeDescriptor.GetConverter(destinationType); System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(destinationType); bool canConvertFrom = converter.CanConvertFrom(value.GetType()); if (!canConvertFrom) { converter = TypeDescriptor.GetConverter(value.GetType()); } if (!(canConvertFrom || converter.CanConvertTo(destinationType))) { string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_NoConverterExists, value.GetType().FullName, destinationType.FullName); throw new InvalidOperationException(message); } try { object convertedValue = (canConvertFrom) ? converter.ConvertFrom(null /* context */, culture, value) : converter.ConvertTo(null /* context */, culture, value, destinationType); return(convertedValue); } catch (Exception ex) { string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_ConversionThrew, value.GetType().FullName, destinationType.FullName); throw new InvalidOperationException(message, ex); } }
protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { string strValue = String.Empty; if (value != null) { if ((bool)value) { strValue = CommonLanguage.Current.BooleanTrue; } else { strValue = CommonLanguage.Current.BooleanFalse; } } return(base.GetFormattedValue(strValue, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context)); }
protected void OnMouseMove(object sender, MouseEventArgs e) { Point x = e.GetPosition(this); Matrix transform = Transform; foreach (Circuit.Terminal i in Symbol.Terminals) { Circuit.Coord tx = layout.MapTerminal(i); Point tp = new Point(tx.x, tx.y); tp = transform.Transform(tp); if ((tp - x).Length < 5.0) { ToolTip = "Terminal '" + i.ToString() + "'"; return; } } TextBlock text = new TextBlock(); Circuit.Component component = Symbol.Component; text.Inlines.Add(new Bold(new Run(component.ToString()))); foreach (PropertyInfo i in component.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(j => j.CustomAttribute <Circuit.Serialize>() != null && (j.CustomAttribute <BrowsableAttribute>() == null || j.CustomAttribute <BrowsableAttribute>().Browsable))) { object value = i.GetValue(component, null); DefaultValueAttribute def = i.CustomAttribute <DefaultValueAttribute>(); if (def == null || !Equals(def.Value, value)) { System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(i.PropertyType); text.Inlines.Add(new Run("\n" + i.Name + " = ")); text.Inlines.Add(new Bold(new Run(tc.ConvertToString(value)))); } } ToolTip = new ToolTip() { Content = text }; }
private static void setPropertyValue(PropertyInfo pi, Type propertyType, object oObj, string value) { if (propertyType == typeof(string)) { pi.SetValue(oObj, value, null); return; } object[] attributes = propertyType.GetCustomAttributes(typeof(System.ComponentModel.TypeConverterAttribute), false); foreach (System.ComponentModel.TypeConverterAttribute converterAttribute in attributes) { System.ComponentModel.TypeConverter converter = (System.ComponentModel.TypeConverter)Activator.CreateInstance(Type.GetType(converterAttribute.ConverterTypeName)); if (converter.CanConvertFrom(value.GetType())) { // good - use the converter to restore the value pi.SetValue(oObj, converter.ConvertFromString(value), null); break; } } }
protected override Resources.PDFImageXObject InitImageXObject(PDFContextBase context, Style style) { Document doc = this.Document; if (null == doc) { throw new NullReferenceException(Errors.ParentDocumentCannotBeNull); } if (null != this.Data) { _xobj = null; if (!string.IsNullOrEmpty(this.ImageKey)) { _xobj = this.Document.GetImageResource(this.ImageKey, this, false); } if (null == _xobj) { string name; if (string.IsNullOrEmpty(this.ImageKey)) { name = "DataImage_" + this.Document.GetIncrementID(PDFObjectTypes.ImageXObject); } else { name = this.ImageKey; } System.ComponentModel.TypeConverter BitmapConverter = TypeDescriptor.GetConverter(typeof(Bitmap)); Bitmap img = (Bitmap)BitmapConverter.ConvertFrom(this.Data.Raw); PDFImageData data = PDFImageData.LoadImageFromBitmap(name, img, this.Compress); _xobj = PDFImageXObject.Load(data, name); this.Document.SharedResources.Add(_xobj); } } return(_xobj); }