Do Non-Static things from Static, C#?

96 views Asked by At

I'm using c# to develop a small UWP app for Windows IoT that is installed on Raspberry pi 3. However, I want to this:

button.Visibility = Visibility.Visible;
button1.Visibility = Visibility.Collpsed;

That code I want to keep it inside a static method :). I haven't found any helpful answer yet. I hope you guys will give me an easy and quick solution.

2

There are 2 answers

0
WraithNath On

As a second option to Kevin's already sufficient answer, similar can be done with extension methods if you are working with one button at a time. You will need a using statement for the namespace the extension method is in.

Extension methods are a way of adding an instance method to an existing class.

see MSDN - Extension Methods

eg:

public static class ButtonExtensions
{
    public static void SetVisibility(this Button button, Visibility visibility)
    {
       button.Visibility = visibility;
    }
}

usage:

public void Test()
{
    Button button = new Button();
    Visibility visibility = Visibility.Collapsed;

    button.SetVisibility(visibility);

    //or
    ButtonExtensions.SetVisibility(button, visibility);
}
0
Kevin Smith On

If you want to make that static you'll have to pass in the buttons

public static void DoStuff(Button button, Button button1)
{
    button.Visibility = Visibility.Visible;
    button1.Visibility = Visibility.Collpsed;
}