2010-04-13 3 views
3

안녕하세요 이것은 How to access a named element of a derived user control in silverlight?과 비슷하지만 차이점은 사용자 정의 컨트롤이 아닌 템플릿 컨트롤에서 상속됩니다.템플릿 컨트롤에서 상속 한 컨트롤에서 명명 된 요소에 액세스하는 방법

<Style TargetType="Problemo:MyBaseControl"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="Problemo:MyBaseControl"> 
        <Grid x:Name="LayoutRoot" Background="White"> 
         <Border Name="HeaderControl" Background="Red" /> 
        </Grid> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

코드 : - - :

나는

XAML MyBaseControl라는 템플릿 제어 할 수 있습니다

public class MyBaseControl : Control 
    { 
     public UIElement Header { get; set; } 

     public MyBaseControl() 
     { 
      DefaultStyleKey = typeof(MyBaseControl); 
     } 

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

      var headerControl = GetTemplateChild("HeaderControl") as Border; 

      if (headerControl != null) 
       headerControl.Child = Header; 

     } 
    } 

나는

MyBaseControl Control에서 상속 myControl라는 또 다른 제어 할 수 있습니다 Xaml : -

<me:MyBaseControl x:Class="Problemo.MyControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    xmlns:me="clr-namespace:Problemo" 
    d:DesignHeight="300" d:DesignWidth="400"> 
    <me:MyBaseControl.Header> 
     <TextBlock Name="xxx" /> 
    </me:MyBaseControl.Header> 
</me:MyBaseControl> 

코드 : -

public partial class MyControl : MyBaseControl 
{ 
    public string Text { get; set; } 

    public MyControl(string text) 
    { 
     InitializeComponent(); 
     Text = text; 
     Loaded += MyControl_Loaded; 
    } 

    void MyControl_Loaded(object sender, RoutedEventArgs e) 
    { 
     base.ApplyTemplate(); 
     xxx.Text = Text; 
    } 
} 

문제는 XXX입니다 null입니다. 코드에서 xxx 컨트롤에 액세스하려면 어떻게합니까?

+0

은 OnApplyTemplate 재정의에서도 xxx == null입니다. –

답변

0

HeaderControl에 액세스하면 ControlTemplate에서 가져옵니다. ControlTemplate의 요소가 만들어져 컨트롤의 시각적 자손으로 추가됩니다. 그런 다음 OnApplyTemplate 메서드가 호출되고 이름을 통해 액세스 할 수 있습니다.

두 번째 경우에는 특히 머리글 속성에 단일 요소를 할당하고 있습니다. 헤더가 명시 적으로 설정되므로이 경우 "명명 된"요소를 가져올 수 없습니다. 당신이, TextBlock의 수과 같이 것 알고있는 경우

당신이 직접 헤더 속성을 캐스팅 수 :

TextBlock tb = this.Header as TextBlock; 
if (tb != null) 
    tb.Text = Text; 

그렇지 않으면, 당신과 같이 당신의 XAML에 텍스트 속성에 TextBlock의 결합 수 :

<me:MyBaseControl.Header> 
<TextBlock Name="xxx" Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type me:MyControl}}, Path=Text}" /> 
</me:MyBaseControl.Header> 

주어진 컨트롤 (예 : TextBlock)에 묶여 있지 않기 때문에 후자의 바인딩 방법이 더 좋은 방법입니다.

관련 문제