2013-12-08 33 views
0

我创建了名为MainControl.xaml的用户控制器。在我的MainWindow.xaml内(这是空的,空白的)我想插入这个MainControl控件。在wpf窗口中使用自定义控件

所以里面装MainWindow的事件,我把

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

但没有任何反应,显然我失去了一些东西

+0

你能还交你的MainWindow的一些XAML? – ChrisK

+0

主窗口是空的,所以它真的没有任何内部xaml值得发布,窗口init。代码和空网格标签。 – panjo

+0

在这种情况下,您可以将网格的内容设置为'bc'。尽管您可能希望直接在XAML中添加控件。 – ChrisK

回答

1

您需要将其添加到实际容器中,以便显示它。例如一个Grid或一个StackPanel。如果你添加一个自定义的clr-namespace,你也可以直接从你的XAML中添加你的控件。

2

您应该将控件添加到窗口(设置这个新的控制作为窗口的内容):

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

我要去承担MainControl,您已经提到实际上是BooksControl是在你的代码,你已经暴露的实例。

是的,你已经在你的代码隐藏从我能看到你什么也没做真正把它添加到布局(特别是考虑到你提到你的而是创造了一个新的实例MainWindow.xaml为空)。

现在,我也要去假设,当你说“但没有任何反应”你的意思是,你的BooksControl不显示您主窗口 - 这是因为,如上所述,你尚未将其添加到布局。

做到这一点的两种主要方式是在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> 

代码隐藏

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