Access CustomControl's element programmatically in WPF

1k Views Asked by At

I have created a custom control which will have only one Grid into it.

Here is the part of the code from 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>

Corresponding MainView.cs is as follows:

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

Now I have created a another project and I want to include this custom control into one of the panel programmatically.

This is what I have done in .cs file from different project , where I wanted to create this CustomControl dynamically.

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;

What exactly I want is , I want to create CustomControl dynamically and then add it to TabItem. So, I want to access Grid in CustomControl and add DataGrid to it programmatically. But OnApplyTemplate() gets called only when the Custom control is displayed in the screen. In my case its giving exception saying "MainViewGrid is null" So, how do I access MainView CustomControl's element in this case or rather call OnApplyTemplate(), so that I can "find" Grid and add DataGrid to it.

0

There are 0 best solutions below