我可以解决您的问题的一种方法是:在 Usercontrol 中使用 EvenHandler 并在 mainView 中订阅它。在用户控件中的每个说按钮上单击都会引发事件。
我刚刚创建了一个示例:
我们在用户控件中有文本框和按钮
这是代码隐藏;
public partial class UserControl1 : UserControl
{
public event EventHandler<EventArgs> CreateNewUserControl = null;
public static int InstanceCount = 0;
public UserControl1()
{
InitializeComponent();
Loaded += new RoutedEventHandler(UserControl1_Loaded);
}
void UserControl1_Loaded(object sender, RoutedEventArgs e)
{
InstanceCount++;
txtControl.Text = "Control - " + InstanceCount;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var handler = CreateNewUserControl;
if (handler != null)
handler.Invoke(sender,e);
}
}
在主视图中:
xml:
<StackPanel x:Name="UserControlTest" Orientation="Vertical" VerticalAlignment="Top" HorizontalAlignment="Right" Grid.Column="1" Grid.RowSpan="2" ScrollViewer.VerticalScrollBarVisibility="Auto" MaxHeight="800" Margin="30">
<RadChartProject:UserControl1 x:Name="UserControl1"/>
</StackPanel>
xml.cs:
public MainPage()
{
InitializeComponent();
UserControl1.CreateNewUserControl += UserControl1_CreateNewUserControl;
}
void UserControl1_CreateNewUserControl(object sender, EventArgs e)
{
if(UserControlTest != null)
{
var control = new UserControl1();
control.CreateNewUserControl += UserControl1_CreateNewUserControl;
UserControlTest.Children.Add(control);
}
}