How to create a function to change the visibility of any given object with the visibility property in C#?

时间:2016-12-07 08:32:13

标签: c# uwp

Is there any way to create a function in C# that can change the visibility of an given object that has the visibility property?

public void changeVisibilityState(Button test)
{
    if (test.Visibility == Visibility.Collapsed)
    {
        test.Visibility = Visibility.Visible;
    }
    else
    {
        test.Visibility = Visibility.Collapsed;
    }
}

Like this but for any object with the visibility property.

2 个答案:

答案 0 :(得分:3)

您可以使用实现Visibility属性的更常见对象。例如UIElement。 来自msdn:

  

UIElement是大多数Windows运行时UI对象的基类   具有视觉外观,可以作为一部分处理基本输入   您应用的用户界面

所以使用这样的东西:

 public void ChangeVisibilityState(UIElement test)
    {
        if (test.Visibility == Visibility.Collapsed)
        {
            test.Visibility = Visibility.Visible;
        }
        else
        {
            test.Visibility = Visibility.Collapsed;
        }
    }

通过这种方式,您可以将任何继承UIElement

的内容传递给此函数

答案 1 :(得分:0)

如你所愿。 具有“可见性”属性的每个对象

public static void changeVisibility(this object obj, Visibility vis) {
    var property = obj.GetType().GetProperty("visibility", BindingFlags.Instance);
    if ( property != null ) {
        property.SetValue(obj, vis);
    }
}