简体   繁体   English

在wpf窗口中使用自定义控件

[英]using custom control inside wpf window

I created user controller named MainControl.xaml. 我创建了一个名为MainControl.xaml的用户控制器。 Inside my MainWindow.xaml (which is empty, blank) I wan to to insert this MainControl control. 在我的MainWindow.xaml(空白,空白)中,我想插入此MainControl控件。

So inside MainWindow loaded event I put 所以在MainWindow加载的事件里面

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var bc = new Controls.BooksControl();
    bc.Visibility = System.Windows.Visibility.Visible;
}

but nothing happens, obviously I'm missing something 但是什么也没发生,很明显我在想什么

You should add your control to the window (set this new control as content of the window): 您应该将控件添加到窗口中(将此新控件设置为窗口的内容):

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var bc = new Controls.BooksControl();
    bc.Visibility = System.Windows.Visibility.Visible;
    this.Content = bc;
}

You need to add it to an actual container, in order to show it. 您需要将其添加到实际容器中才能显示它。 For instance a Grid or an StackPanel. 例如网格或StackPanel。 If you add a custom clr-namespace you can also add your Control directly from inside your XAML. 如果添加自定义clr-namespace ,则还可以直接从XAML内部添加控件。

I'm going to assume the MainControl that you've mentioned is actually the BooksControl that is instantiated in your code that you've exposed. 我将假设您提到的MainControl实际上是在您公开的代码中实例化的BooksControl

Yes, you've created a new instance in your code-behind but from what I can see you haven't done anything to actually add it to the layout (particularly given that you've mentioned that your MainWindow.xaml is empty). 是的,您已经在代码背后创建了一个新实例,但是据我所知,您实际上并没有做任何事情将其添加到布局中 (特别是考虑到您提到MainWindow.xaml为空)。

Now, I'm also going to assume that when you say " but nothing happens " that you mean that your BooksControl isn't showing in your MainWindow - this is because, as described, you haven't added it to the layout. 现在,我还要假设当您说“ 但什么也没有发生 ”时,是指您的BooksControl没有显示在MainWindow中 -这是因为,如前所述,您尚未将其添加到布局中。

The two main ways to do this are in the XAML or in the code behind: 实现此目的的两种主要方法是在XAML或后面的代码中:

XAML: XAML:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xlmns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        controls="clr-namespace:Controls;assembly=Controls">

    <controls:BooksControl/>

</Window>

Code Behind 背后的代码

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var bc = new Controls.BooksControl();

    // set the content of the Window to be the BooksControl
    // assuming the BooksControl has default Visibility of Visible
    this.Content = bc;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM