将用户控件添加到WPF窗口

75

我创建了一个用户控件,但是当我尝试将它添加到窗口的XAML中时,Intellisense没有找到它,并且我无法弄清楚如何将其添加到窗口中。

4个回答

89

你需要在window标签内添加一个引用。类似于:

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

当你添加xmlns:controls="时,智能感知应该会启动,使这一过程更加容易。

然后你可以使用以下代码添加控件:

<controls:CustomControlClassName ..... />

13
现在已经是2015年了,设计师们还不能自动完成这个吗?真是见鬼! - BlueRaja - Danny Pflughoeft
2
@MartinHarris 在“yourassemblyname”中应该写什么? - Mahavirsinh Padhiyar
显然,您的程序集名称是输出文件的名称(大多数情况下是dll)。如果输出的dll文件名为awesome.assembly.dll,则“yourassemblyname”为“awesome.assembly”。 - honzakuzel1989
2
VS2013 设计师在省略程序集后感到更加愉快。 - stackuser83
现在,VS2017通过提供一个灯泡来添加命名空间,修复了<CustomControlClassName。 :-) - David Ching
1
我该如何知道程序集的名称? - Yessir

14

你可能需要添加命名空间

<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>

13

确保你的控件所属的命名空间有一个命名空间定义(xmlns)。

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

8
+1 意味着“有时智能感知很蠢”,请确保项目实际上无法编译和运行,我已经追踪不到 Visual Studio 多少次告诉我我的 xaml 无效了,而只需要重新构建它以使其重新考虑。 - Martin Harris
@MartinHarris 是的! 我也把我的控件放在了一个Grid中,最初忘记给它一个Grid.Row/Grid.Column分配和Grid.RowSpan/Grid.ColumnSpan。 - orangecaterpillar

8
这是我让它正常工作的方法:
用户控件 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();
        }
    } }

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>

哇,你太棒了!非常感谢。 - fatihyildizhan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接