c# - WPF 如何从 DataTemplate 访问控件

标签 c# .net wpf

我有一个包含网格的数据模板,在网格内我有一个组合框。

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

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

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

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

最佳答案

我知道的三种方式。

1.使用FindName

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

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

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

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

3.在可视化树中查找

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

关于c# - WPF 如何从 DataTemplate 访问控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4586106/

相关文章:

c# - 将 Char[] 转换为 List<byte> (c#)

c# - 在 uml 中表示 C# 自动实现的属性

c# - 向应用程序用户发送通知/请求(Facebook - C#)

c# - 有没有一种简单的方法可以将多个项目添加到解决方案中?

.net - IEndpointBehavior ApplyClientBehavior 方法在行为添加到端点行为后未执行

c# - 闪屏上的淡入淡出效果

c# - 银光。将样式项绑定(bind)到数据上下文

c# - 在 WPF 中使用图像和图标

c# - 数据库中的重复项

C# 在运行时获取定义字典的类型