2011-01-03 6 views
4

나는 그리드를 포함하고 그리드 안에 콤보 박스가있는 datatemplate을 가지고있다.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> 

나는 스타일을 통해 해당 템플릿을 참조하는 표가 있습니다.

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

기본적으로 DataContext를 설정하기 위해 myCombo의 코드를 통해 어떻게 액세스 할 수 있습니까?

답변

4

우선, 리소스 (ShowAsExpanded)와 ContentPresenter의 사용법 사이의 관계를 찾을 수 없습니다. 그러나 잠시 동안 DynamicResource가 ShowAsExpanded를 가리켜 야한다고 가정 해 봅시다.

코드를 통해 콤보 박스에 액세스 할 수 없으며 액세스해서도 안됩니다. 스타일을 사용하는 표에 datacontext를 바인딩해야합니다. 그렇게하고 싶지 않다면 런타임에 콘텐츠를 찾아서 자식 콤보 박스를 검색해야합니다.

+0

Interesing. 나는 wpf에 상당히 새로운 것이다. 표에서 datacontext를 설정하면 템플릿의 콤보 박스에 어떻게 전파됩니까? 또한, 내 템플릿에 2 콤보 상자가있는 경우 어떻게 각각의 데이터 인터페이스가 다른 경우 각 콤보의 datacontext가 바인딩되어 있다고 가정합니까? – pdiddy

+2

datacontext는 자식의 datacontext를 명시 적으로 설정하지 않는 한 하위에 전파됩니다. 그리드에 datacontext를 설정하면 ContentPresenter (및 아래의 모든 컨트롤)가 해당 datacontext를 공유하고 바인드 할 수 있습니다. –

+0

2 개의 다른 콜렉션을 통해 바인딩해야하는 템플릿에 2 개의 콤보 박스가있는 경우 어떻게됩니까? – pdiddy

18

내가 아는 세 가지 방법.

1. 한 FindName

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

2.Add 시각적 트리에서이

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

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

3.Find 그것에서 콤보 및 액세스 그것에로드 이벤트

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

고맙습니다. 매우 도움이되었지만, Geert van Horrik의 대답을 통해 코드를 통해 액세스하는 것이 올바른 방법이 아니라고 생각하게되었습니다. – pdiddy

+0

@pdiddy : You 're absolutely right :) 행운을 빈다. –

관련 문제