简体   繁体   中英

Do Non-Static things from Static, C#?

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.

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;
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM