Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I show an object in multiple panels?

Tags:

c#

winforms

I was wondering how could I use a custom object in more than one panel.

I made a panelModified object (extends from Panel) and want to place it in two normal panels, so when the object change its status, both panels display the updated information.

In my case the "panelModified" is a panel with some Buttons and an embeded video in it.

Here is the code:

panelPreview = new PanelPreview(file); (panelModified object)

panel1.Controls.Add(panelPreview);

panel2.Controls.Add(panelPreview);

it only shows in the panel2 :(

like image 389
HoNgOuRu Avatar asked Oct 14 '22 00:10

HoNgOuRu


2 Answers

You can't put the same control in two different places.

The solution here is to create a "model" object that has all the information that can change. Then you create two copies of PanelPreview that point to the same Model.

Your model should implemention INotifyPropertyChanged so it can tell the panel when something has changed.

For your purposes, a "model" is the same thing as a "business object" or "data object".

like image 74
Jonathan Allen Avatar answered Oct 31 '22 17:10

Jonathan Allen


Your custom object that you're showing has to be able to notify that it's values are changing (ie implements INotifyPropertyChanged).

Then, you can change your PanelPreview to bind on your object.

This way, you can have as much instances as you like - when you change in one instance, the INotifyPropertyChanged will trigger the displaying on all others.

For example:

public class CustomClass : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        private void OnPropertyChanged(string propName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }

        private string mProp;
        public string Prop
        {
            get
            {
                return mProp;
            }
            set
            {
                if (value != mProp)
                {
                    mProp = value;
                    OnPropertyChanged("Prop");
                }
            }
        }
    }

And then in your binding place you bind to it. Here I'm binding to textboxes, but you could do it with whatever:

CustomClass c = new CustomClass();
textBox1.DataBindings.Add("Text", c, "Prop", true, DataSourceUpdateMode.OnPropertyChanged);
textBox2.DataBindings.Add("Text", c, "Prop", true, DataSourceUpdateMode.OnPropertyChanged);
like image 44
veljkoz Avatar answered Oct 31 '22 18:10

veljkoz