views:

2841

answers:

4

Hi guys,

First off, I'm new to WPF and C# so maybe the issue I have is really easy to fix. But I'm kinda stuck at the moment.

Let me explain my problem.

I have a WPF Window and two usercontrols (Controls and ContentDisplayer).

The usercontrol Controls, wich contains some buttons, is added in the XAML of the Window. Nothing special here.

Window.XAML

<nv:Controls/>

Now, what I want to do is when a user is pressing a button in Controls, ContentDisplayer needs to be added to the Scatterview I have in my Window.

I solved the problem by adding the buttons to the Window, and not using the usercontrol Controls. But this is not what I want.

Window.XAML.CS

private static void Button_ContactChanged(object sender, ContactEventArgs e)
    {
      object ob = Application.LoadComponent(new Uri(
      "NVApril;component\\XAML\\ContentDisplayer.xaml",
      System.UriKind.RelativeOrAbsolute));

    //Set a unique name to the UserControl
      string name = String.Format("userControl{0}",
      SurfaceWindow1_Scatterview.Items.Count);
      UserControl userControl = ob as UserControl;
      userControl.Name = name;

    //Add the new control to the Scatterview
      SurfaceWindow1_Scatterview.Items.Add(userControl);
      SurfaceWindow1_Scatterview.RegisterName(name, userControl);
    }

So the real question is: How do I add a usercontrol to the Window by pressing a button in an other usercontrol?

Thanks,

Toner

A: 

Within Controls expose an event that is fired when you want to add a new control.

public event EventHandler AddControl;

private void RaiseAddControl()
{
 if (AddControl!= null)
 {
  AddControl(this, EventArgs.Empty);
 }
}

Now sink that event in your Window

yourControl.AddControl += ContactChanged
MrTelly
A: 

Hi MrTelly,

Thanks for your quick reply, I tried your code but it doesn't seem to work for me at the moment. Maybe I'm forgetting something. I added the RaiseAddControl to the button event, and it fires correctly. But the AddControl stays null.

Also, I can't figure out how to use the AddControl in the Window.

yourControl.AddControl += ContactChanged

Could you give me some more information on how I could fix this problems?

(Sorry for being noobish, but I really appreciate your feedback).

Thanks,

Toner

A: 

In your window, it sounds like you need to add the event to the instances of Controls.

<local:ContentDisplayer>
...
  <nv:Controls AddControl="ContactChanged"/>
...

Then in your ContactChanged event handler you can instantiate a new Controls control and add it to whatever collection you're using like in your Button_ContactChanged event handler above.

Let me know if you need further clarification.

Jeff Wain
A: 

Thank you MrTelly and Jeff. It seems to be working now : )