[英]how to add tab item in one user control from another window + WPF
我有一个父窗口 WMain,在 Stackpanel 中有一个 UserControl(Dashboard)。 在仪表板中,我有一个 Tabcontrol,它将填充在同一仪表板中的按钮 Click of a Button 上。 仪表板的 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 添加到仪表板中。 有没有办法从子级创建父 UserControl 的 TabItem。
使用EventHandler 委托。 您可以使用它来publish
和subscribe
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);
}
}
}
主窗口.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
,因为我使用的控件从代码中应该很明显,但是,如果您需要它,我可以提供它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.