WPF如何从DataTemplate访问控件

pdi*_*ddy 6 .net c# wpf

我有一个datatemplate包含一个网格,在网格内我有一个组合框.

<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>
Run Code Online (Sandbox Code Playgroud)

然后,我有一个网格,通过样式引用该模板.

<Grid>
    <ContentPresenter Name="_contentPresenter" Style="{DynamicResource StyleWithCollapse}" Content="{Binding}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

如何通过代码访问myCombo来基本设置其DataContext?

Fre*_*lad 25

我知道的三种方式.

1.使用FindName

ComboBox myCombo =
    _contentPresenter.ContentTemplate.FindName("myCombo",
                                               _contentPresenter) as ComboBox;
Run Code Online (Sandbox Code Playgroud)

2.将Loaded事件添加到ComboBox并从那里访问它

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

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

3.在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;
}
Run Code Online (Sandbox Code Playgroud)


Gee*_*rik 5

首先,我甚至找不到Resource(ShowAsExpanded)与ContentPresenter内部用法之间的关系.但就目前而言,我们假设Dy​​namicResource应该指向ShowAsExpanded.

您不能也不应该通过代码访问组合框.您应该将datacontext绑定到使用该样式的网格.如果您不想这样做,则必须在运行时查找内容并搜索子组合框.

  • 只要您没有显式设置该子级的datacontext,就会将datacontext传播给子级.因此,如果在Grid上设置datacontext,ContentPresenter(以及下面的所有控件)将共享该datacontext并可以绑定到它. (2认同)