在WPF中,动态加载的元素如何访问其父元素?

时间:2009-03-17 10:03:42

标签: wpf xaml dependency-injection inversion-of-control

Window1.xaml 中,我有菜单和显示区域:

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

Window1.xaml.cs 中,我在菜单项中动态加载:

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

MenuItemEmployees.xaml.cs 中,我注入Window1,但如何访问其元素?

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);
        }
    }
}

解答:

好吧,我想通了,这只是一个疏忽,我忘了为window1创建一个内部变量。但是我会把这段代码放在这里,可能很有趣,很容易将主窗口传递给控件,​​这样动态添加的控件就可以访问窗口上的其他元素,这是一个穷人的依赖注入没有接口:

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 个答案:

答案 0 :(得分:1)

尝试这样的事情

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

ContainerFromItem是一种静态方法,可以执行您想要的操作,请参阅Microsoft blurb here