是否有可能知道wpf中某个样式的setter可用?

时间:2011-04-10 23:28:22

标签: c# wpf

我已经下载了一个有类的程序集。该类公开了一个样式属性以允许自定义外观。是否有可能知道它将允许创建样式对象的所有可能的setter属性? (例如,通过观察disaassmbly等)。

编辑:如果不可能,我也在寻找指南(例如,查找类暴露的所有dependencyproperty,查看PutStyle的MSIL代码等)。

2 个答案:

答案 0 :(得分:2)

当我读到你的问题时,我并不确切知道你的情况。再次查看之后,听起来您正试图找到可以在对象的样式中设置的属性。这意味着您将对依赖项对象上可用的非只读依赖项属性感兴趣。当然,有一点需要注意,对象可能不一定使用所有属性来渲染自身。因此,如果你设置一些属性并且似乎没有任何改变,不要感到惊讶。

只需使用反射搜索所有DependencyProperty字段并获取值(如果对象遵循声明依赖项属性的约定)。您可以使用它来获取此类属性。

public static IEnumerable<DependencyProperty> GetDependencyProperties(DependencyObject owner)
{
    var type = owner.GetType();
    var flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy;
    return type.GetFields(flags)
               .Where(fi => fi.FieldType == typeof(DependencyProperty))
               .Select(fi => fi.GetValue(null))
               .Cast<DependencyProperty>();
}

// get the non-readonly dependency properties
var writableDPs = GetDependencyProperties(myObject)
    .Where(dp => !dp.ReadOnly);

答案 1 :(得分:0)

杰夫·梅尔卡多的建议听起来很不错,例如我只是在自定义控件上使用它:

var props = typeof(PanAndZoomControl).GetProperties()
    .Where(x => x.CanWrite)
    .Select(x => x.Name);
MessageBox.Show(String.Join(", ", props));

A screenshot

我使用逗号分隔符使其更紧凑,您只需使用File.WriteAllLines()或类似内容将其输出到文本文件。