WPF如何从DataTemplate访问控件
我有一个datatemplate包含一个网格,在网格内我有一个combobox。
然后我有一个网格,通过样式引用该模板。
如何通过代码访问myCombo来基本设置其DataContext?
首先,我甚至找不到Resource(ShowAsExpanded)与ContentPresenter内部用法之间的关系。 但就目前而言,我们假设DynamicResource应该指向ShowAsExpanded。
您不能也不应该通过代码访问combobox。 您应该将datacontext绑定到使用该样式的网格。 如果您不想这样做,则必须在运行时查找内容并搜索子combobox。
我知道的三种方式。
1.使用FindName
ComboBox myCombo = _contentPresenter.ContentTemplate.FindName("myCombo", _contentPresenter) as ComboBox;
2.将Loaded事件添加到ComboBox并从那里访问它
3.在Visual Tree中找到它
private void SomeMethod() { ComboBox myCombo = GetVisualChild(_contentPresenter); } private T GetVisualChild(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 (v); } if (child != null) { break; } } return child; }
你需要使用FindName。 查看http://msdn.microsoft.com/en-us/library/system.windows.frameworktemplate.findname.aspx