2010-12-01 4 views
12

가장 일반적인 WPF 요구 사항 중 하나가되어야 할 부분에 난처한 생각이 들었습니다. this question을 읽었지만 솔루션을 구현하지 않았습니다. 여기 ControlTemplate 내의 컨트롤에 중점을두기 (파트 2)

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       xmlns:local="clr-namespace:WpfTest"> 
    <Style TargetType="{x:Type local:CustomControl}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
     <ControlTemplate TargetType="{x:Type local:CustomControl}"> 
      <Border> 
      <TextBox x:Name="myTextBox" /> 
      </Border> 
      <ControlTemplate.Triggers> 
      <Trigger Property="IsFocused" 
        Value="True"> 
       <Setter Property="FocusManager.FocusedElement" 
         Value="{Binding ElementName=myTextBox}" /> 
       <Setter TargetName="myTextBox" 
         Property="Background" 
         Value="Green" /> 
      </Trigger> 
      </ControlTemplate.Triggers> 
     </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
    </Style> 
</ResourceDictionary> 

이 CustomControl의 인스턴스가 들어있는 창을위한 마크 업입니다 : 여기

는 lookless 제어를위한 마크 업의 여기

<Window x:Class="WpfTest.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfTest" 
     Title="Window1" Height="300" Width="300"> 

    <local:CustomControl x:Name="CCtl" /> 
</Window> 

와 코드 숨김입니다 :

public partial class Window1 : Window 
{ 
    public Window1() 
    { 
     InitializeComponent(); 
     Loaded += (RoutedEventHandler)delegate { CCtl.Focus(); }; 
    } 
} 

Window1이로드되면 텍스트 상자가 녹색으로 바뀝니다. ger works)하지만 텍스트 상자가 아닌 CCtl에 포커스가 유지됩니다. 의심 할 여지없이 이것은 다음과 같은 데이터 오류를 표시하는 출력과 관련이있다 :

Cannot find source for binding with reference 'ElementName=myTextBox'. BindingExpression:(no path); DataItem=null; target element is 'CustomControl' (Name='CCtl'); target property is 'FocusedElement' (type 'IInputElement').

나는이 오류가 나타나는 이유를 아무 생각도 없어. 감사의 말을 전하는 포인터. 감사합니다.

답변

12

하는 대신 트리거이를 사용해보십시오 :

<Trigger Property="IsFocused" Value="True"> 
    <Setter TargetName="myTextBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=myTextBox}" /> 
</Trigger> 

오류는 FocusedElement 속성이 적용되는 위치 이름이 범위에 포함되지 않기 때문에이합니다 MyTextBox을 찾을 수 있음을 말하고있다. 이 경우 CCtl 인스턴스 자체에 있으며 이는 자체 템플릿 내부에서 볼 수 없습니다. 템플리트 내부의 속성에 속성을 설정하면 Binding이 명명 된 요소를 찾을 수 있습니다.

+0

예, 그게 전부입니다. 정말로 감사합니다. –

0

내가 잘못했을 수도 있지만 귀하의 문제는 귀하의 속성 트리거 때문인 것으로 생각됩니다.

TextBox을 포커스로 설정하면 템플릿 부모에서 Trigger이 유효하게 무효화되므로 트리거가 풀리고 TextBox에 포커스를 설정하여 되돌릴 수 있습니다 (따라서 초점을 맞추지 않습니다).

+1

하지만 오류 메시지에 대해 걱정하지 않습니까? –

관련 문제