panjo
panjo

Reputation: 3515

using custom control inside wpf window

I created user controller named MainControl.xaml. Inside my MainWindow.xaml (which is empty, blank) I wan to to insert this MainControl control.

So inside MainWindow loaded event I put

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

Upvotes: 0

Views: 172

Answers (3)

Chris Badman
Chris Badman

Reputation: 501

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.

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

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.

The two main ways to do this are in the XAML or in the code behind:

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

Upvotes: 1

ChrisK
ChrisK

Reputation: 1218

You need to add it to an actual container, in order to show it. For instance a Grid or an StackPanel. If you add a custom clr-namespace you can also add your Control directly from inside your XAML.

Upvotes: 1

Yurii
Yurii

Reputation: 4911

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

Upvotes: 2

Related Questions