Windows Forms application, how to interact between custom controls?

I have three user controls. Here is their description: 1) The first user control (ucCountry) contains a combobox that displays country names from an xml file.

2) The second user control (ucChannelType) contains two switches for choosing a TV and another for choosing the type of radio channel.

3) The third user control (ucChannels) will populate all channels in which the country name is provided by ucCountry and the type provided by ucChannelType

Now, how to establish a connection between this user control in the form. I need to separate custom elements from a form. Therefore, I need to use events. But if ucCountry fires an event (for example, a CountryChanged event), and ucChannels sign the event, how to get the channel type from ucChannelType.

Thanks in advance...

+5
source share
3 answers

The best solution is to add properties to your user controls. there can be no fields in the background, getters will simply receive data from the internal standard control property.

+3
source

ucCountry, . - :

public Country SelectedCountry
{
    get
    {
        return (Country) myComboBox.SelectedItem;
    }
}

, , get.

, ucCountry.CountryChanged :

public delegate void CountryChangedDelegate(Country sender)

public event CountryChangedDelegate CountryChanged;

ucChannels:

public void ucCountry_CountryChanged(Country sender)
{
    //do something with the new country
}

ucChannels:

myUcCountry.CountryChanged += new CountryChangedDelegate(ucCountry_CountryChanged);
+2

, , , . :

public static void Test()
{
    var a = new A();
    var b = new B();
    var c = new C() {a = a, b = b};
    a.OnChange += c.Changed;
    b.OnChange += c.Changed;
    a.State = "CA";
    b.ChannelType = "TV";
}

class A
{
    private string _state;

    public string State
    {
        get { return _state; }
        set
        {
            _state = value;
            if (OnChange != null) OnChange(this, EventArgs.Empty);
        }
    }

    public event EventHandler<EventArgs> OnChange;
}

class B
{
    private string _channelType;

    public string ChannelType
    {
        get { return _channelType; }
        set
        {
            _channelType = value;
            if (OnChange != null) OnChange(this, EventArgs.Empty);
        }
    }

    public event EventHandler<EventArgs> OnChange;
}

class C
{
    public A a { get; set; }
    public B b { get; set; }
    public void Changed(object sender, EventArgs e)
    {
        Console.WriteLine("State: {0}\tChannelType: {1}", a.State, b.ChannelType);
    }
}
0

All Articles