我创建了一个自定义控件,其中只有一个 Grid。
这是代码的一部分Generic.xaml
<Style TargetType="{x:Type local:MainView}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MainView }">
<Grid x:Name="**PART_MyGrid**" Background="Black" Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}">
<ContentPresenter Content="{TemplateBinding Content}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
对应MainView.cs
如下:
[TemplatePart(Name = "PART_MyGrid", Type = typeof(Grid))]
public class MainView : ContentControl
{
private Grid MainViewGrid;
static MainView()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MainView), new FrameworkPropertyMetadata(typeof(MainView)));
}
public override void OnApplyTemplate()
{
//This Function never gets called
base.OnApplyTemplate();
//Find the grid in the template once it's applied
MainViewGrid = base.Template.FindName("**PART_MyGrid**", this) as Grid;
//We can subscribe to its events
}
public void setGrid(DataGrid dtGrid)
{
***//Exception saying MainViewGrid is null***
MainViewGrid.Children.Add(dtGrid);
}
}
现在我创建了另一个项目,我想以编程方式将此自定义控件包含到其中一个面板中。
这就是我在不同项目的 .cs 文件中所做的,我想在其中动态创建这个 CustomControl。
CustomControlLib.MainView m_View = new CustomControlLib.MainView();
***//... Code to create One Datagrid programmatically ...***
m_View.setGrid(programmatically_created_dataGrid);
theTabItem.Content = m_View;
theTabItem.DataContext = m_View.DataContext;
我真正想要的是,我想CustomControl
动态创建,然后将其添加到TabItem
. 所以,我想以编程方式访问Grid
并添加它CustomControl
。DataGrid
但OnApplyTemplate()
仅当自定义控件显示在屏幕中时才被调用。在我的情况下,它给出了异常说"MainViewGrid is null"
所以,在这种情况下我如何访问 MainView CustomControl 的元素,或者更确切地说调用OnApplyTemplate()
,以便我可以“找到” Grid 并将 DataGrid 添加到它。