首页 文章

将用户控件添加到wpf窗口

提问于
浏览
59

我有一个我创建的用户控件,但是当我在窗口中将它添加到XAML时,Intellisense没有把它拿起来,我无法弄清楚如何将它添加到窗口中 .

4 回答

  • 12

    您需要在窗口标记内添加引用 . 就像是:

    xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
    

    (当你添加xmlns:controls =“intellisense应该启动以使这一点更容易)

    然后你可以添加控件:

    <controls:CustomControlClassName ..... />
    
  • 2

    您可能需要添加namespace

    <Window x:Class="UserControlTest.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:UserControlTest"
        Title="User Control Test" Height="300" Width="300">
        <local:UserControl1 />
    </Window>
    
  • 69

    几个提示:首先,确保顶部有一个包含控件所在命名空间的xmlns .

    xmlns:myControls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
    <myControls:thecontrol/>
    

    第二,有时intellisense是愚蠢的 .

  • 15

    这就是我开始工作的方式:

    用户控制WPF

    <UserControl x:Class="App.ProcessView"
                 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="300" d:DesignWidth="300">
        <Grid>
    
        </Grid>
    </UserControl>
    

    用户控制C#

    namespace App {
        /// <summary>
        /// Interaction logic for ProcessView.xaml
        /// </summary>
        public partial class ProcessView : UserControl // My custom User Control
        {
            public ProcessView()
            {
                InitializeComponent();
            }
        } }
    

    MainWindow WPF

    <Window x:Name="RootWindow" x:Class="App.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:app="clr-namespace:App"
            Title="Some Title" Height="350" Width="525" Closing="Window_Closing_1" Icon="bouncer.ico">
        <Window.Resources>
            <app:DateConverter x:Key="dateConverter"/>
        </Window.Resources>
        <Grid>
            <ListView x:Name="listView" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <app:ProcessView />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </Window>
    

相关问题