简体   繁体   中英

How do I access a usercontrol instance in another usercontrol instance?

I have two UserControls: Player and Playlist.

Player.cs

namespace Music_Player
{
    public partial class Player : UserControl
    {
        public int currentSongIndex = 0;
        public WindowsMediaPlayer player = new WindowsMediaPlayer();
        
        public Player()
        {
            InitializeComponent();
            player.settings.autoStart = false;
        }

        private void playButton_Click(object sender, EventArgs e)
        {
            if (playButton.Text == "Play")
            {
                Play();
            }
            else
            {
                Pause();
            }
        }

        public void Play()
        {
            if (CheckSongs()) { return; }
            playButton.Text = "Pause";
            player.controls.play();
        }
...

Playlist.cs

namespace Music_Player
{
    public partial class Playlist : UserControl
    {
        public Playlist()
        {
            InitializeComponent();
        }

        private void playlistTitle_Click(object sender, EventArgs e)
        {
            player.Play(); // THIS IS WHERE I WANT TO USE THE player INSTANCE OF Player()
        }
...

The UserControls are both children of another UC which is in my Form.

How can I use the player which is an instance of Player() inside Playlist?

You probably want to handle events in the form the controls are in, not within the control itself. The form would have a reference to both controls and likely whatever they are controlling. That's where things should be connected.

Suppose you have added a player1 and a playList1 to the form.

To call the method in another UserControl, you can define a property in Form.cs to access the player1 instance.

public Player PlayerInstance
{
    get { return player1; }
}

Then you can call Player.Play() in Playlist.cs via the code as followed.

private void playlistTitle_Click(object sender, EventArgs e)
{
    Form1 form1 = (Form1)this.FindForm();
    form1.PlayerInstance.Play();
}

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