在Windows Phone中的页面中添加用户控件

时间:2012-06-18 12:01:57

标签: windows-phone-7.1

我有一个Windows Phone应用程序,我需要将一个用户控件添加到其中一个页面。我想像在asp.net页面中那样添加它,而不是弹出窗口。如何将此用户控件添加到页面?

2 个答案:

答案 0 :(得分:4)

假设您的UserControl的格式类似于:

<UserControl x:Class="UserControlExample.NameReporter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

<!-- Controls here -->

</UserControl>

当你创建一个新的UserControl并且后面的代码类似于

时,它应该默认
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace UserControlExample
{
    public partial class NameReporter : UserControl
    {
        public NameReporter()
        {
            InitializeComponent();
        }

        // your custom methods here
    }
}

然后,您应该可以使用类似于

的代码将其添加到页面中
<Grid xmlns:src="clr-namespace:UserControlExample" 
        Background="White" Margin="0,50,0,0">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="Auto"/>
  </Grid.RowDefinitions>
  <src:NameReporter Grid.Row="0"/>
  <src:NameReporter Grid.Row="1" Margin="0,15,0,0"/>
</Grid>

只需更改clr-namespace:后的命名空间和src:

后的控件名称

您可以将xmlns:标记放入<phone:PhoneApplicationPage>标记,而不是在整个表单中使用控件(而不仅仅是在网格中),您可以将src更改为您的任何内容希望将其称为。<​​/ p>

如果正确创建UserControl,编译解决方案应该意味着它也会出现在您的工具箱中以供使用,因此您只需拖动即可。下降。

有关更全面的示例,请参阅参考资料。

  

参考文献:

     

http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol%28v=VS.95%29.aspx

答案 1 :(得分:3)

对于Windows Phone 8和Windows Phone 8.1,我可以通过执行以下操作来完成此操作:

创建用户控件。在这个例子中,我创建了一些矩形来模仿经典的移动菜单按钮。

Your usercontrol

构建解决方案。项目将更新,您现在将在工具箱中看到您的用户控件。

Toolbox

只需将用户控件拖出工具箱,然后将其放入您希望使用用户控件的XAML页面中。

UserControl in use