Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...