WPF How to access control from DataTemplate

I have a datatemplate which contains a grid and inside the grid I have a combobox.

<DataTemplate x:Key="ShowAsExpanded">
        <Grid>                
            <ComboBox Name ="myCombo" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Top" Margin="5"
                      IsSynchronizedWithCurrentItem="True"
                      ItemsSource="{Binding}"
                      ItemTemplate="{StaticResource MyItems}">
                <ComboBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel />
                    </ItemsPanelTemplate>
                </ComboBox.ItemsPanel>
            </ComboBox>

        </Grid>
    </DataTemplate>

I then I have a grid that refers to that template through styling.

<Grid>
    <ContentPresenter Name="_contentPresenter" Style="{DynamicResource StyleWithCollapse}" Content="{Binding}" />
</Grid>

How can I access through code behing the myCombo to basically set its DataContext?


Solution 1:

Three ways which I know of.

1.Use FindName

ComboBox myCombo =
    _contentPresenter.ContentTemplate.FindName("myCombo",
                                               _contentPresenter) as ComboBox;

2.Add the Loaded event to the ComboBox and access it from there

<ComboBox Name ="myCombo" Loaded="myCombo_Loaded" ...

private void myCombo_Loaded(object sender, RoutedEventArgs e)
{
    ComboBox myCombo = sender as ComboBox; 
    // Do things..
}

3.Find it in the Visual Tree

private void SomeMethod()
{
    ComboBox myCombo = GetVisualChild<ComboBox>(_contentPresenter);
}
private T GetVisualChild<T>(DependencyObject parent) where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
        {
            child = GetVisualChild<T>(v);
        }
        if (child != null)
        {
            break;
        }
    }
    return child;
}

Solution 2:

First of all, I can't even find the relation between the Resource (ShowAsExpanded) and the usage inside the ContentPresenter. But for the moment, let's assume that the DynamicResource should point to ShowAsExpanded.

You can't and shouldn't access the combobox via code. You should bind the datacontext to the grid that uses the style. If you don't want to do that, you will have to find the content at runtime and search for the child combobox.

Solution 3:

you need to use FindName. check out http://msdn.microsoft.com/en-us/library/system.windows.frameworktemplate.findname.aspx