2011-12-22 4 views
0

사용자가 주소를 입력 할 수 있도록 AddressInput 컨트롤을 만들었습니다. 컨트롤은 사용 된 위치에 따라 모양이 달라 지므로 AddressTemplate이라는 DataTemplate 속성을 제공했습니다.ContentPresenter에 적용된 DataTemplate의 요소는 어떻게 찾습니까?

기본 스타일은 다음과 같습니다 : 내 주소 데이터 템플릿

<Style TargetType="{x:Type addressUI:AddressInput}"> 
    <Setter Property="AddressTemplate" 
      Value="{StaticResource DefaultAddressTemplate}" /> 

    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type addressUI:AddressInput}"> 
       <GroupBox Header="Address"> 
        <ContentPresenter ContentTemplate="{Binding Path=AddressTemplate, RelativeSource={RelativeSource TemplatedParent}}" 
             Content="{Binding Path=Address, RelativeSource={RelativeSource TemplatedParent}}" 
             x:Name="PART_AddressPresenter" /> 
       </GroupBox> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

모두 ("PART_CountriesList"라는 이름의) 국가를 선택하는 콤보 박스가 포함됩니다. 선택 영역이 변경 될 때 발생하는 코드 숨김 액션이 필요합니다. 즉, SelectionChanged 이벤트를 후크해야합니다. 내 AddressInput 내에서 PART_CountriesList를 AddressTemplate에서 찾아야합니다.

나는이 같은 "PART_AddressPresenter"ContentPresenter를 얻을 수 있습니다 : 지금은 AddressTemplate 안에 포함 "PART_CountriesList"를 얻는 방법

public override void OnApplyTemplate() 
{ 
    base.OnApplyTemplate(); 

    var addressPresenter = Template.FindName("PART_AddressPresenter", this) as ContentPresenter; 
} 

를?

나는 노력이 :

VAR countriesList = AddressTemplate.FindName ("PART_CountriesList", addressPresenter);

addressPresenter에 아직 템플릿이 적용되지 않았기 때문에 예외가 발생합니다. ContentPresenter에는 OnApplyTemplate 재정의 (override)가 있습니다 만,이 용도로 그것을 확장하는 것은 어리석은 것처럼 보입니다.

ContentPresenter를 확장하면 OnApplyTemplate 메서드가 실행될 때마다 이벤트를 발생시키는 새로운 재사용 가능한 버전을 만들 수 있습니다. 이것은 아마 내 문제를 해결할 수 있지만 그것은 미친 것 같습니다. 더 좋은 방법이 있습니까?

답변

0

사람이 작업을 수행 할 수있는 "권리"방법이 있는지 궁금 해요,하지만 FindName와 나는 항상이 같은 의지 끝 : 당신이 기다리고 있기 때문하지만 깜박임이 발생할 수 있습니다

Dispatcher.BeginInvoke(new Action(() => 
{ 
    // Call FindName here 
}), System.Windows.Threading.DispatcherPriority.Render); 

데이터 템플릿이 완료되고 렌더링되도록 렌더링 될 때까지는 코드를 연습해야하므로, 수행하려는 작업이 컨트롤의 모양에 영향을 주면 항상 좋은 옵션은 아닙니다.

관련 문제