在 C# 中使用反射访问和修改 xaml 元素

Jam*_*rke 2 c# reflection xaml windows-phone-7

我有一个模型,它有许多属性,这些属性可能为空,也可能不为空,具体取决于数据是否可用于远程服务器上的这些特定属性。

我正在构建一个简单的 Windows Phone 应用程序,该应用程序可以在手机上提供更容易访问的版本的信息。我发现在没有设置上面模型的属性的情况下,该值不会显示(显示空白),但标签仍然显示。

在考虑了许多不同的替代方案(包括大量的 if 语句,呃)之后,我决定,如果我在 xaml 中设置特定属性的名称以匹配我正在查看的数据模型的属性,那么我让系统实时分析数据模型的属性以及我的 xaml 的元素。如果我的 xaml 中的属性与模型中的属性名称匹配,并且模型为空,我可以将可见性转为折叠。如果模型不为空,则使其可见。因此,我可以获得一个干净、动态的解决方案,仅显示实际可用的数据。

这是代码

PropertyInfo[] properties = data.GetType().GetProperties();

foreach (PropertyInfo property in properties)
{

    FieldInfo view = this.GetType().GetField(property.Name);

    if (view != null)
    {
        if (property.GetValue(data, null) == null)
        {
            object aView = view.GetValue(this);
            aView.GetType().GetProperty("Visibility").SetValue(aView, "Collapsed", null);
        }
        else
        {
            object aView = view.GetValue(this);
            aView.GetType().GetProperty("Visibility").SetValue(aView, "Visible", null);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我遇到了障碍。我不知道如何访问 xaml 元素。我尝试过使用

this.GetType().GetProperties()
this.GetType().GetFields()
this.GetType().GetMembers()
Run Code Online (Sandbox Code Playgroud)

找到我正在寻找的元素,但它们没有出现在其中任何一个中。我有什么遗漏的吗?

有没有更好、更美观的方法呢?

在此先感谢您的帮助。

Col*_*inE 5

如果您在 XAML 中命名了元素,如下所示:

<Grid>
  <TextBlock x:Name="txt" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

您可以通过FindName方法找到它们:

TextBlock txt = this.FindName("txt") as TextBlock;
Run Code Online (Sandbox Code Playgroud)

不需要反思!