views:

337

answers:

1

In Window1.xaml I have menu and display area:

<Menu x:Name="TheMenu" Width="Auto" Height="25" DockPanel.Dock="Top"/>
<ItemsControl x:Name="MainContent" DockPanel.Dock="Top"/>

In Window1.xaml.cs I dynamically load in a menu item:

MenuItem menuItemEmployees = new MenuItemEmployees(this);
TheMenu.Items.Add(menuItemEmployees);

In MenuItemEmployees.xaml.cs I inject Window1 but how do I access its elements?

using System.Windows.Controls;
using System.Windows;

namespace TestContainer1
{
    public partial class MenuItemEmployees : MenuItem
    {
        public MenuItemEmployees(Window1 window1)
        {
            InitializeComponent();
        }

        private void Create_Employee(object sender, System.Windows.RoutedEventArgs e)
        {
            TextBlock textBlock = new TextBlock();
            textBlock.Text = "New Customer";

            //how can I access my ItemsControl element in "Window1" here?
            //pseudo code:
            Window1.Children["MainContent"].Add(textBlock);
        }
    }
}

ANSWER:

Ok, I figured it out, this was just an oversight, I forgot to create an internal variable for window1. But I'll leave this code here, might be interesting, very easy to pass the main window down into controls so that the dynamically added controls can access other elements on the window, kind of a poor man's dependency injection without the interfaces:

using System.Windows.Controls;
using System.Windows;

namespace TestContainer1
{
    public partial class MenuItemEmployees : MenuItem
    {
        private Window1 _window1;

        public MenuItemEmployees(Window1 window1)
        {
            InitializeComponent();
            _window1 = window1;
        }

        private void Create_Employee(object sender, System.Windows.RoutedEventArgs e)
        {
            TextBlock textBlock = new TextBlock();
            textBlock.Text = "New Customer";

            _window1.MainContent.Items.Add(textBlock);
        }
    }
}
+1  A: 

Try something like this

Menu yourMenu = ItemContainerGenerator.ContainerFromItem(this) as Menu;
Window yourWindow = Menu.Parent as Window;

ContainerFromItem is a static method that does what you want, see the Microsoft blurb here.

MrTelly