【问题标题】:How can I find out, whether a certain type has a string converter attached?我怎样才能知道某个类型是否附加了字符串转换器?
【发布时间】:2010-09-29 13:25:45
【问题描述】:

问题来了:

我有某个对象的属性。该属性属于类型 t。我需要找出是否可以将字符串值附加到此属性。

例如:我有一个 Windows.Controls.Button 的实例。我需要一种机制,它将为属性 Button.Background 返回 true,但为 Button.Template 返回 false。

有人可以帮忙吗?非常感谢

【问题讨论】:

  • Button 没有背景属性...您是指Text 属性吗?
  • 好吧,忘记按钮 - 以网格为例。当您将字符串值“#00556677”传递给它的背景属性时,它会被转换为画笔。但是您不能将某些字符串值传递给它的 Template 属性。这就是我需要了解任何对象的任何属性的内容。

标签: c# wpf typeconverter


【解决方案1】:

我认为你把问题引向了错误的方向:

该属性不直接接受String:如果存在转换器,则该属性实际上被转换为好的类型。

然后您可以使用此代码查看转换器是否存在:

public static bool PropertyCheck(Type theTypeOfTheAimedProperty, string aString)
{
   // Checks to see if the value passed is valid.
   return TypeDescriptor.GetConverter(typeof(theTypeOfTheAimedProperty))
            .IsValid(aString);
}

您可能也会对这些页面感兴趣:

  1. http://msdn.microsoft.com/en-us/library/aa970913.aspx
  2. http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx

【讨论】:

  • 非常感谢 - 这为我指明了一个很好的方向,尽管我需要的确切代码是:return TypeDescriptor.GetConverter(typeof(theTypeOfTheAimedProperty)).CanConvertFrom(typeof(String));
  • 不错!玩得开心:-)
【解决方案2】:
public static bool PropertyCheck(this object o, string propertyName)
{
    if (string.IsNullOrEmpty(propertyName))
        return false;
    Type type = (o is Type) ? o as Type : o.GetType();

    PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);

    if (pi != null && pi.PropertyType == typeof(string))
        return true;

    return false;
}

然后像这样调用它:

object someobj = new Object();
if (someobj.PropertyCheck("someproperty"))
     // do stuff

或者你可以这样做:

Type type = typeof(someobject);
if (type.PropertyCheck("someproperty"))

这有一些限制,因为您无法检查 Type 类型本身的属性,但如果需要,您可以随时制作另一个版本。

我想这就是你想要的,希望对你有帮助

【讨论】:

  • 此示例对所有类型为字符串的属性返回 true。这不正是我所需要的。我需要找出所有属性,它们的值可以通过字符串在 XAML 中设置。请参阅我在上一篇文章中给出的背景和模板示例。无论如何感谢您的反应
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 2016-03-26
  • 1970-01-01
  • 2011-01-10
  • 2021-01-05
相关资源
最近更新 更多