WPF使用自定义控件UserControl

大佬们基本上都在讲怎么自定义控件,却怎么也没有说明怎么使用这些个自定义的控件,然后看完教程的本小白只能干瞪眼..可能大佬们不屑这样基础的东西
首先新建一个用户控件UserControl1.xaml,这个会用几下VS的应该都没有难度。

<UserControl x:Class="BlackBird.Control.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="600" d:DesignWidth="600">
    <Grid>
          <!--此处省略代码,拷贝网络上的代码到这里,或者自己写-->
    </Grid>
</UserControl>

然后是在需要添加该控件的窗体中的操作..
方法一:在xmal文件中添加
首先、要引用用户控件的命名空间 xmlns:bird="clr-namespace:BlackBird.Control"

<bird:UserControl1 x:Name="userControl1" />

然后、把用户控件添加到窗体中

<Window x:Class="WpfApplicationDemo.UserControlDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:bird="clr-namespace:BlackBird.Control"
        Title="UserControlDemo" Height="300" Width="300" Loaded="Window_Loaded">
    <Grid>
        <bird:UserControl1 x:Name="userControl11" />
    </Grid>
</Window>

方法二:在cs代码中添加

比如我们把用户控件放到StackPanel面板中

<StackPanel Name="stackPanel1"></StackPanel>

在后台代码中,引用命名空间,实例化用户控件,添加到面板容器中即可

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            UserControl1 demo = new UserControl1();
            this.stackPanel1.Children.Add(demo);
        }

完成

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

  1. 纺织知识 说道:

    现在不怎么看得进去这样的技术文章

    1. 鬼手六 说道:

      给自己做记录和给需要的人查阅

  2. 趣知识 趣知识 说道:

    好长时间没用.net了

    1. 鬼手六 说道:

      用DotNet不久还有很多问题要解决..

  3. 周松松博客 说道:

    每次看到技术文章就头疼,呵呵