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