如何在另一个窗口+ WPF中的一个用户控件中添加选项卡项

时间:2013-10-12 07:07:09

标签: c# wpf user-controls

我有一个父窗口WMain,在Stackpanel内有一个UserControl(仪表板)。在仪表板中,我有一个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();

工作正常。我想在按钮上单击Estimate Usercontrol将另一个TabItem添加到仪表板中。是否有办法从Child创建父UserControl的TabItem。

1 个答案:

答案 0 :(得分:0)

使用EventHandler Delegate。您可以将其用于publishsubscribe event通知,并传递可选参数(在此方案中为UserControl)。

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

<强> MainWindow.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因为我使用的控件应该从代码中显而易见,但是,如果你需要它我可以提供它。