Search code examples
c#xamlwindows-phone-8windows-phone

How to link or reference a UI control such as a button in code


I've been searching for and trying to figure out how to link a variable to a UI control, so that I can use the variable to perform that particular's UI's actions in code.

For instance, I have a button named NextButton in my MainPage.xaml. I want to define a variable, say nextButton of type Button, so that I can perform a button action, say nextButton.Content in my c# class. It seems this can only be done in the MainPage.xaml and even with that I can 't figure out how to link the button variable to a particular button.

To make myself even clearer, let me just say that you can do something like this in android by using findViewById.


Solution

  • This might be slightly off what you're after, but if you just want to alter the content of a button, you could use data binding and then provide access point for other classes to the data directly.

    To me, it sounds like you want to directly alter another view from another view and that doesn't sound very "MVCey". Have a common underlying data model instead and alter that and have the buttons figure out what they should be doing. If your button performs methods or it's state is handled by methods.

    If you really want to provide an access point to the buttons directly, you could just have something like

    public abstract class CommonUIControls {
        public static Button nextButton = null;
    }
    
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            CommonUIControls.nextButton = nextButton;
        }
    }
    

    However, I would not suggest thsi.