如何将XAML用户控件放在网格中

我有以下main.xaml和usercontrol。

我需要在网格的第二行,第二列上放置几次用户控件,通过使用visual studio它不会允许拖放用户控件,所以我想我必须通过代码来做,我只是不知道怎么样

MainPage.xaml中

             

用户控件

               

你的意思是这样的吗?

   

在这种情况下是UserControl所在的CLR命名空间的别名。它根据上下文定义在XAML的顶部,在标记内。

例如,

  

MainPage.xaml中

            

UserControl1.xaml

             

MainPage.xaml ,我使用命名空间绑定登录UserControl:xmlns:UC =“clr-namespace:Test.Views”,因为我在名为“ Views ”的文件夹中有我的usercontrol。

    

Login.cs

 public partial class Login : UserControl { public event EventHandler BtnLoginClick; public Login() { InitializeComponent(); } private void btnLogin_Click(object sender, RoutedEventArgs e) { string userName = txtUserName.Text; string userPassword = txtUserPassword.Password.Trim(); if (userName != null && userName != string.Empty && userPassword != null && userPassword != string.Empty) { if (this.BtnLoginClick != null) { this.BtnLoginClick(this, e); } } else { MessageBox.Show("Invalid username or password"); } } 

}

最后,不要忘记使用MainPage.xaml中的事件处理程序从Login Usercontrol捕获按钮单击事件以执行其他操作。

MainPage.xaml中

  

这里的“BtnLoginClick”是Login.xaml [User Control]中定义的事件处理程序。

当我创建“Login_BtnLoginClick”时,为此“BtnLoginClick”事件创建新事件。

MainPage.cs

 private void Login_BtnLoginClick(object sender, EventArgs e) { Messagebox.Show("Event captured successfully"); ////Here you can add your stuffs... }