0

我有一个父窗口 WMain,在 Stackpanel 中有一个 UserControl(Dashboard)。在仪表板中,我有一个 Tabcontrol,它将填充在同一仪表板中的按钮单击按钮上。仪表板的 TabItem 是另一个 UserControl (uscEstimate)。我正在使用下面提到的代码填充 TabControl

        TabItem Tab = new TabItem();
        Tab.Header = est;
        tbcMain.Items.Add(Tab);
        uscEstimate estimate = new uscEstimate();
        Tab.Content = new uscEstimate();
        Tab.Focus();

它工作正常。我想在单击估计用户控件的按钮时将另一个 TabItem 添加到仪表板中。有没有办法从子级创建父级用户控件的 TabItem。

4

1 回答 1

0

使用EventHandler 委托。您可以使用它publish和通知并传递可选参数(在这种情况下是您的)subscribeeventUserControl

uscEstimate.xaml.cs

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

public partial class uscEstimate : UserControl
{
    // Declare an EventHandler delegate that we will use to publish and subscribe to our event
    // We declare this as taking a UserControl as the event argument
    // The UserControl will be passed along when the event is raised
    public EventHandler<UserControl> AddNewItemEventHandler;

    public uscEstimate()
    {
        InitializeComponent();
    }

    // Create a new UserControl and raise (publish) our event
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var control = new uscEstimate();
        RaiseAddNewItemEventHandler(control);
    }

    // We use this to raise (publish) our event to anyone listening (subscribed) to the event
    private void RaiseAddNewItemEventHandler(UserControl ucArgs)
    {
        var handler = AddNewItemEventHandler;
        if (handler != null)
        {
            handler(this, ucArgs);
        }
    }
}

主窗口.xaml.cs

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

public sealed partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.CreateAndAddTabItem("MainWindow");
    }

    // This manages the creation and addition of new tab items to the tab control
    // It also sets up the subscription to the event in the uscEstimate control
    private void CreateAndAddTabItem(string header)
    {
        var tab = new TabItem { Header = header };
        tbcMain.Items.Add(tab);
        var uscEstimate = new uscEstimate();
        uscEstimate.AddNewItemEventHandler += AddNewItemEventHandler;
        tab.Content = uscEstimate;
        tab.Focus();
    }

    // This handles the raised AddNewItemEventHandler notifications sent from uscEstimate
    private void AddNewItemEventHandler(object sender, UserControl userControl)
    {
        this.CreateAndAddTabItem("uscEstimate");
    }
}

我省略了xaml这个,因为我使用的控件从代码中应该是显而易见的,但是,如果你需要它,我可以提供它。

于 2013-10-12T12:19:41.657 回答