简体   繁体   中英

How to pass window and string parameter from code behind into User Control

I have a bit off header that I need global to a few files so I have made a user control (I can't use the main window as this isn't global to all files) however there's two parameters that my user control needs, ScreenName and MainWindow to navigate on the home button click. Here is what I have tried so far:

public Header(MainWindow mainWindow, string screenName)
    {
        InitializeComponent();
        DataContext = this;
        ScreenName = screenName;
        MainWindow = mainWindow;
        ScreenNameTextBlock.Text = ScreenName;
    }

    public string ScreenName { get; set; }
    public MainWindow MainWindow { get; set; }

    private void Hyperlink_OnClick(object sender, RoutedEventArgs e)
    {
        //need to navigate home here
        MainWindow.LoadScreenByCode("Menu");
    }

You can probably assume the corresponding XAML as it's just a hyperlink and a textblock, but if you need it let me know.

I can include the user control like so:

<controls:Header x:Name="Header"></controls:Header>

But I can't figure out how to assign the parameters. If I try in the codebehind I can access the values like this:

Header.MainWindow = Shell;
Header.ScreenName = "Name";

But this causes the values to be null. Sorry if this is an easy issue, I am new to UserControls.

To access the main window of your application you should get the running instance of it as the following:

     MainWindow myRunnningMainWindow = (Application.Current.MainWindow as MainWindow);

     if(myRunningWindow!=null)
        {
         //Do what you want with the main window
        }

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